The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/netinet/tcp_input.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

    1 /*-
    2  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
    3  *      The Regents of the University of California.  All rights reserved.
    4  *
    5  * Redistribution and use in source and binary forms, with or without
    6  * modification, are permitted provided that the following conditions
    7  * are met:
    8  * 1. Redistributions of source code must retain the above copyright
    9  *    notice, this list of conditions and the following disclaimer.
   10  * 2. Redistributions in binary form must reproduce the above copyright
   11  *    notice, this list of conditions and the following disclaimer in the
   12  *    documentation and/or other materials provided with the distribution.
   13  * 4. Neither the name of the University nor the names of its contributors
   14  *    may be used to endorse or promote products derived from this software
   15  *    without specific prior written permission.
   16  *
   17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
   18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
   21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   27  * SUCH DAMAGE.
   28  *
   29  *      @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
   30  * $FreeBSD: releng/5.4/sys/netinet/tcp_input.c 147668 2005-06-29 21:41:03Z simon $
   31  */
   32 
   33 #include "opt_ipfw.h"           /* for ipfw_fwd         */
   34 #include "opt_inet.h"
   35 #include "opt_inet6.h"
   36 #include "opt_ipsec.h"
   37 #include "opt_mac.h"
   38 #include "opt_tcpdebug.h"
   39 #include "opt_tcp_input.h"
   40 #include "opt_tcp_sack.h"
   41 
   42 #include <sys/param.h>
   43 #include <sys/kernel.h>
   44 #include <sys/mac.h>
   45 #include <sys/malloc.h>
   46 #include <sys/mbuf.h>
   47 #include <sys/proc.h>           /* for proc0 declaration */
   48 #include <sys/protosw.h>
   49 #include <sys/signalvar.h>
   50 #include <sys/socket.h>
   51 #include <sys/socketvar.h>
   52 #include <sys/sysctl.h>
   53 #include <sys/syslog.h>
   54 #include <sys/systm.h>
   55 
   56 #include <machine/cpu.h>        /* before tcp_seq.h, for tcp_random18() */
   57 
   58 #include <vm/uma.h>
   59 
   60 #include <net/if.h>
   61 #include <net/route.h>
   62 
   63 #include <netinet/in.h>
   64 #include <netinet/in_pcb.h>
   65 #include <netinet/in_systm.h>
   66 #include <netinet/in_var.h>
   67 #include <netinet/ip.h>
   68 #include <netinet/ip_icmp.h>    /* for ICMP_BANDLIM             */
   69 #include <netinet/icmp_var.h>   /* for ICMP_BANDLIM             */
   70 #include <netinet/ip_var.h>
   71 #include <netinet/ip6.h>
   72 #include <netinet/icmp6.h>
   73 #include <netinet6/in6_pcb.h>
   74 #include <netinet6/ip6_var.h>
   75 #include <netinet6/nd6.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>
   83 #ifdef TCPDEBUG
   84 #include <netinet/tcp_debug.h>
   85 #endif /* TCPDEBUG */
   86 
   87 #ifdef FAST_IPSEC
   88 #include <netipsec/ipsec.h>
   89 #include <netipsec/ipsec6.h>
   90 #endif /*FAST_IPSEC*/
   91 
   92 #ifdef IPSEC
   93 #include <netinet6/ipsec.h>
   94 #include <netinet6/ipsec6.h>
   95 #include <netkey/key.h>
   96 #endif /*IPSEC*/
   97 
   98 #include <machine/in_cksum.h>
   99 
  100 static const int tcprexmtthresh = 3;
  101 tcp_cc  tcp_ccgen;
  102 
  103 struct  tcpstat tcpstat;
  104 SYSCTL_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats, CTLFLAG_RW,
  105     &tcpstat , tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
  106 
  107 static int log_in_vain = 0;
  108 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
  109     &log_in_vain, 0, "Log all incoming TCP connections");
  110 
  111 static int blackhole = 0;
  112 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
  113         &blackhole, 0, "Do not send RST when dropping refused connections");
  114 
  115 int tcp_delack_enabled = 1;
  116 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
  117     &tcp_delack_enabled, 0,
  118     "Delay ACK to try and piggyback it onto a data packet");
  119 
  120 #ifdef TCP_DROP_SYNFIN
  121 static int drop_synfin = 0;
  122 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
  123     &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
  124 #endif
  125 
  126 static int tcp_do_rfc3042 = 1;
  127 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_RW,
  128     &tcp_do_rfc3042, 0, "Enable RFC 3042 (Limited Transmit)");
  129 
  130 static int tcp_do_rfc3390 = 1;
  131 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
  132     &tcp_do_rfc3390, 0,
  133     "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
  134 
  135 static int tcp_insecure_rst = 0;
  136 SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_RW,
  137     &tcp_insecure_rst, 0,
  138     "Follow the old (insecure) criteria for accepting RST packets.");
  139 
  140 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, reass, CTLFLAG_RW, 0,
  141             "TCP Segment Reassembly Queue");
  142 
  143 static int tcp_reass_maxseg = 0;
  144 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxsegments, CTLFLAG_RDTUN,
  145            &tcp_reass_maxseg, 0,
  146            "Global maximum number of TCP Segments in Reassembly Queue");
  147 
  148 int tcp_reass_qsize = 0;
  149 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, cursegments, CTLFLAG_RD,
  150            &tcp_reass_qsize, 0,
  151            "Global number of TCP Segments currently in Reassembly Queue");
  152 
  153 static int tcp_reass_maxqlen = 48;
  154 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxqlen, CTLFLAG_RW,
  155            &tcp_reass_maxqlen, 0,
  156            "Maximum number of TCP Segments per individual Reassembly Queue");
  157 
  158 static int tcp_reass_overflows = 0;
  159 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, overflows, CTLFLAG_RD,
  160            &tcp_reass_overflows, 0,
  161            "Global number of TCP Segment Reassembly Queue Overflows");
  162 
  163 struct inpcbhead tcb;
  164 #define tcb6    tcb  /* for KAME src sync over BSD*'s */
  165 struct inpcbinfo tcbinfo;
  166 struct mtx      *tcbinfo_mtx;
  167 
  168 static void      tcp_dooptions(struct tcpcb *, struct tcpopt *, u_char *,
  169                      int, int, struct tcphdr *);
  170 
  171 static void      tcp_pulloutofband(struct socket *,
  172                      struct tcphdr *, struct mbuf *, int);
  173 static int       tcp_reass(struct tcpcb *, struct tcphdr *, int *,
  174                      struct mbuf *);
  175 static void      tcp_xmit_timer(struct tcpcb *, int);
  176 static void      tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
  177 static int       tcp_timewait(struct tcptw *, struct tcpopt *,
  178                      struct tcphdr *, struct mbuf *, int);
  179 
  180 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
  181 #ifdef INET6
  182 #define ND6_HINT(tp) \
  183 do { \
  184         if ((tp) && (tp)->t_inpcb && \
  185             ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0) \
  186                 nd6_nud_hint(NULL, NULL, 0); \
  187 } while (0)
  188 #else
  189 #define ND6_HINT(tp)
  190 #endif
  191 
  192 /*
  193  * Indicate whether this ack should be delayed.  We can delay the ack if
  194  *      - there is no delayed ack timer in progress and
  195  *      - our last ack wasn't a 0-sized window.  We never want to delay
  196  *        the ack that opens up a 0-sized window and
  197  *              - delayed acks are enabled or
  198  *              - this is a half-synchronized T/TCP connection.
  199  */
  200 #define DELAY_ACK(tp)                                                   \
  201         ((!callout_active(tp->tt_delack) &&                             \
  202             (tp->t_flags & TF_RXWIN0SENT) == 0) &&                      \
  203             (tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
  204 
  205 /* Initialize TCP reassembly queue */
  206 uma_zone_t      tcp_reass_zone;
  207 void
  208 tcp_reass_init()
  209 {
  210         tcp_reass_maxseg = nmbclusters / 16;
  211         TUNABLE_INT_FETCH("net.inet.tcp.reass.maxsegments",
  212             &tcp_reass_maxseg);
  213         tcp_reass_zone = uma_zcreate("tcpreass", sizeof (struct tseg_qent),
  214             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
  215         uma_zone_set_max(tcp_reass_zone, tcp_reass_maxseg);
  216 }
  217 
  218 static int
  219 tcp_reass(tp, th, tlenp, m)
  220         register struct tcpcb *tp;
  221         register struct tcphdr *th;
  222         int *tlenp;
  223         struct mbuf *m;
  224 {
  225         struct tseg_qent *q;
  226         struct tseg_qent *p = NULL;
  227         struct tseg_qent *nq;
  228         struct tseg_qent *te = NULL;
  229         struct socket *so = tp->t_inpcb->inp_socket;
  230         int flags;
  231 
  232         INP_LOCK_ASSERT(tp->t_inpcb);
  233 
  234         /*
  235          * XXX: tcp_reass() is rather inefficient with its data structures
  236          * and should be rewritten (see NetBSD for optimizations).  While
  237          * doing that it should move to its own file tcp_reass.c.
  238          */
  239 
  240         /*
  241          * Call with th==NULL after become established to
  242          * force pre-ESTABLISHED data up to user socket.
  243          */
  244         if (th == NULL)
  245                 goto present;
  246 
  247         /*
  248          * Limit the number of segments in the reassembly queue to prevent
  249          * holding on to too many segments (and thus running out of mbufs).
  250          * Make sure to let the missing segment through which caused this
  251          * queue.  Always keep one global queue entry spare to be able to
  252          * process the missing segment.
  253          */
  254         if (th->th_seq != tp->rcv_nxt &&
  255             (tcp_reass_qsize + 1 >= tcp_reass_maxseg ||
  256              tp->t_segqlen >= tcp_reass_maxqlen)) {
  257                 tcp_reass_overflows++;
  258                 tcpstat.tcps_rcvmemdrop++;
  259                 m_freem(m);
  260                 return (0);
  261         }
  262 
  263         /*
  264          * Allocate a new queue entry. If we can't, or hit the zone limit
  265          * just drop the pkt.
  266          */
  267         te = uma_zalloc(tcp_reass_zone, M_NOWAIT);
  268         if (te == NULL) {
  269                 tcpstat.tcps_rcvmemdrop++;
  270                 m_freem(m);
  271                 return (0);
  272         }
  273         tp->t_segqlen++;
  274         tcp_reass_qsize++;
  275 
  276         /*
  277          * Find a segment which begins after this one does.
  278          */
  279         LIST_FOREACH(q, &tp->t_segq, tqe_q) {
  280                 if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
  281                         break;
  282                 p = q;
  283         }
  284 
  285         /*
  286          * If there is a preceding segment, it may provide some of
  287          * our data already.  If so, drop the data from the incoming
  288          * segment.  If it provides all of our data, drop us.
  289          */
  290         if (p != NULL) {
  291                 register int i;
  292                 /* conversion to int (in i) handles seq wraparound */
  293                 i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
  294                 if (i > 0) {
  295                         if (i >= *tlenp) {
  296                                 tcpstat.tcps_rcvduppack++;
  297                                 tcpstat.tcps_rcvdupbyte += *tlenp;
  298                                 m_freem(m);
  299                                 uma_zfree(tcp_reass_zone, te);
  300                                 tp->t_segqlen--;
  301                                 tcp_reass_qsize--;
  302                                 /*
  303                                  * Try to present any queued data
  304                                  * at the left window edge to the user.
  305                                  * This is needed after the 3-WHS
  306                                  * completes.
  307                                  */
  308                                 goto present;   /* ??? */
  309                         }
  310                         m_adj(m, i);
  311                         *tlenp -= i;
  312                         th->th_seq += i;
  313                 }
  314         }
  315         tcpstat.tcps_rcvoopack++;
  316         tcpstat.tcps_rcvoobyte += *tlenp;
  317 
  318         /*
  319          * While we overlap succeeding segments trim them or,
  320          * if they are completely covered, dequeue them.
  321          */
  322         while (q) {
  323                 register int i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
  324                 if (i <= 0)
  325                         break;
  326                 if (i < q->tqe_len) {
  327                         q->tqe_th->th_seq += i;
  328                         q->tqe_len -= i;
  329                         m_adj(q->tqe_m, i);
  330                         break;
  331                 }
  332 
  333                 nq = LIST_NEXT(q, tqe_q);
  334                 LIST_REMOVE(q, tqe_q);
  335                 m_freem(q->tqe_m);
  336                 uma_zfree(tcp_reass_zone, q);
  337                 tp->t_segqlen--;
  338                 tcp_reass_qsize--;
  339                 q = nq;
  340         }
  341 
  342         /* Insert the new segment queue entry into place. */
  343         te->tqe_m = m;
  344         te->tqe_th = th;
  345         te->tqe_len = *tlenp;
  346 
  347         if (p == NULL) {
  348                 LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
  349         } else {
  350                 LIST_INSERT_AFTER(p, te, tqe_q);
  351         }
  352 
  353 present:
  354         /*
  355          * Present data to user, advancing rcv_nxt through
  356          * completed sequence space.
  357          */
  358         if (!TCPS_HAVEESTABLISHED(tp->t_state))
  359                 return (0);
  360         q = LIST_FIRST(&tp->t_segq);
  361         if (!q || q->tqe_th->th_seq != tp->rcv_nxt)
  362                 return (0);
  363         SOCKBUF_LOCK(&so->so_rcv);
  364         do {
  365                 tp->rcv_nxt += q->tqe_len;
  366                 flags = q->tqe_th->th_flags & TH_FIN;
  367                 nq = LIST_NEXT(q, tqe_q);
  368                 LIST_REMOVE(q, tqe_q);
  369                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
  370                         m_freem(q->tqe_m);
  371                 else
  372                         sbappendstream_locked(&so->so_rcv, q->tqe_m);
  373                 uma_zfree(tcp_reass_zone, q);
  374                 tp->t_segqlen--;
  375                 tcp_reass_qsize--;
  376                 q = nq;
  377         } while (q && q->tqe_th->th_seq == tp->rcv_nxt);
  378         ND6_HINT(tp);
  379         sorwakeup_locked(so);
  380         return (flags);
  381 }
  382 
  383 /*
  384  * TCP input routine, follows pages 65-76 of the
  385  * protocol specification dated September, 1981 very closely.
  386  */
  387 #ifdef INET6
  388 int
  389 tcp6_input(mp, offp, proto)
  390         struct mbuf **mp;
  391         int *offp, proto;
  392 {
  393         register struct mbuf *m = *mp;
  394         struct in6_ifaddr *ia6;
  395 
  396         IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
  397 
  398         /*
  399          * draft-itojun-ipv6-tcp-to-anycast
  400          * better place to put this in?
  401          */
  402         ia6 = ip6_getdstifaddr(m);
  403         if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
  404                 struct ip6_hdr *ip6;
  405 
  406                 ip6 = mtod(m, struct ip6_hdr *);
  407                 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
  408                             (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
  409                 return IPPROTO_DONE;
  410         }
  411 
  412         tcp_input(m, *offp);
  413         return IPPROTO_DONE;
  414 }
  415 #endif
  416 
  417 void
  418 tcp_input(m, off0)
  419         register struct mbuf *m;
  420         int off0;
  421 {
  422         register struct tcphdr *th;
  423         register struct ip *ip = NULL;
  424         register struct ipovly *ipov;
  425         register struct inpcb *inp = NULL;
  426         u_char *optp = NULL;
  427         int optlen = 0;
  428         int len, tlen, off;
  429         int drop_hdrlen;
  430         register struct tcpcb *tp = 0;
  431         register int thflags;
  432         struct socket *so = 0;
  433         int todrop, acked, ourfinisacked, needoutput = 0;
  434         u_long tiwin;
  435         struct tcpopt to;               /* options in this segment */
  436         struct rmxp_tao tao;            /* our TAO cache entry */
  437         int headlocked = 0;
  438 #ifdef IPFIREWALL_FORWARD
  439         struct m_tag *fwd_tag;
  440 #endif
  441         int rstreason; /* For badport_bandlim accounting purposes */
  442 
  443         struct ip6_hdr *ip6 = NULL;
  444 #ifdef INET6
  445         int isipv6;
  446 #else
  447         const int isipv6 = 0;
  448 #endif
  449 
  450 #ifdef TCPDEBUG
  451         /*
  452          * The size of tcp_saveipgen must be the size of the max ip header,
  453          * now IPv6.
  454          */
  455         u_char tcp_saveipgen[40];
  456         struct tcphdr tcp_savetcp;
  457         short ostate = 0;
  458 #endif
  459 
  460 #ifdef INET6
  461         isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
  462 #endif
  463         bzero(&tao, sizeof(tao));
  464         bzero((char *)&to, sizeof(to));
  465 
  466         tcpstat.tcps_rcvtotal++;
  467 
  468         if (isipv6) {
  469 #ifdef INET6
  470                 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
  471                 ip6 = mtod(m, struct ip6_hdr *);
  472                 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
  473                 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
  474                         tcpstat.tcps_rcvbadsum++;
  475                         goto drop;
  476                 }
  477                 th = (struct tcphdr *)((caddr_t)ip6 + off0);
  478 
  479                 /*
  480                  * Be proactive about unspecified IPv6 address in source.
  481                  * As we use all-zero to indicate unbounded/unconnected pcb,
  482                  * unspecified IPv6 address can be used to confuse us.
  483                  *
  484                  * Note that packets with unspecified IPv6 destination is
  485                  * already dropped in ip6_input.
  486                  */
  487                 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
  488                         /* XXX stat */
  489                         goto drop;
  490                 }
  491 #else
  492                 th = NULL;              /* XXX: avoid compiler warning */
  493 #endif
  494         } else {
  495                 /*
  496                  * Get IP and TCP header together in first mbuf.
  497                  * Note: IP leaves IP header in first mbuf.
  498                  */
  499                 if (off0 > sizeof (struct ip)) {
  500                         ip_stripoptions(m, (struct mbuf *)0);
  501                         off0 = sizeof(struct ip);
  502                 }
  503                 if (m->m_len < sizeof (struct tcpiphdr)) {
  504                         if ((m = m_pullup(m, sizeof (struct tcpiphdr))) == 0) {
  505                                 tcpstat.tcps_rcvshort++;
  506                                 return;
  507                         }
  508                 }
  509                 ip = mtod(m, struct ip *);
  510                 ipov = (struct ipovly *)ip;
  511                 th = (struct tcphdr *)((caddr_t)ip + off0);
  512                 tlen = ip->ip_len;
  513 
  514                 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
  515                         if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
  516                                 th->th_sum = m->m_pkthdr.csum_data;
  517                         else
  518                                 th->th_sum = in_pseudo(ip->ip_src.s_addr,
  519                                                 ip->ip_dst.s_addr,
  520                                                 htonl(m->m_pkthdr.csum_data +
  521                                                         ip->ip_len +
  522                                                         IPPROTO_TCP));
  523                         th->th_sum ^= 0xffff;
  524 #ifdef TCPDEBUG
  525                         ipov->ih_len = (u_short)tlen;
  526                         ipov->ih_len = htons(ipov->ih_len);
  527 #endif
  528                 } else {
  529                         /*
  530                          * Checksum extended TCP header and data.
  531                          */
  532                         len = sizeof (struct ip) + tlen;
  533                         bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
  534                         ipov->ih_len = (u_short)tlen;
  535                         ipov->ih_len = htons(ipov->ih_len);
  536                         th->th_sum = in_cksum(m, len);
  537                 }
  538                 if (th->th_sum) {
  539                         tcpstat.tcps_rcvbadsum++;
  540                         goto drop;
  541                 }
  542 #ifdef INET6
  543                 /* Re-initialization for later version check */
  544                 ip->ip_v = IPVERSION;
  545 #endif
  546         }
  547 
  548         /*
  549          * Check that TCP offset makes sense,
  550          * pull out TCP options and adjust length.              XXX
  551          */
  552         off = th->th_off << 2;
  553         if (off < sizeof (struct tcphdr) || off > tlen) {
  554                 tcpstat.tcps_rcvbadoff++;
  555                 goto drop;
  556         }
  557         tlen -= off;    /* tlen is used instead of ti->ti_len */
  558         if (off > sizeof (struct tcphdr)) {
  559                 if (isipv6) {
  560 #ifdef INET6
  561                         IP6_EXTHDR_CHECK(m, off0, off, );
  562                         ip6 = mtod(m, struct ip6_hdr *);
  563                         th = (struct tcphdr *)((caddr_t)ip6 + off0);
  564 #endif
  565                 } else {
  566                         if (m->m_len < sizeof(struct ip) + off) {
  567                                 if ((m = m_pullup(m, sizeof (struct ip) + off))
  568                                                 == 0) {
  569                                         tcpstat.tcps_rcvshort++;
  570                                         return;
  571                                 }
  572                                 ip = mtod(m, struct ip *);
  573                                 ipov = (struct ipovly *)ip;
  574                                 th = (struct tcphdr *)((caddr_t)ip + off0);
  575                         }
  576                 }
  577                 optlen = off - sizeof (struct tcphdr);
  578                 optp = (u_char *)(th + 1);
  579         }
  580         thflags = th->th_flags;
  581 
  582 #ifdef TCP_DROP_SYNFIN
  583         /*
  584          * If the drop_synfin option is enabled, drop all packets with
  585          * both the SYN and FIN bits set. This prevents e.g. nmap from
  586          * identifying the TCP/IP stack.
  587          *
  588          * This is a violation of the TCP specification.
  589          */
  590         if (drop_synfin && (thflags & (TH_SYN|TH_FIN)) == (TH_SYN|TH_FIN))
  591                 goto drop;
  592 #endif
  593 
  594         /*
  595          * Convert TCP protocol specific fields to host format.
  596          */
  597         th->th_seq = ntohl(th->th_seq);
  598         th->th_ack = ntohl(th->th_ack);
  599         th->th_win = ntohs(th->th_win);
  600         th->th_urp = ntohs(th->th_urp);
  601 
  602         /*
  603          * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options,
  604          * until after ip6_savecontrol() is called and before other functions
  605          * which don't want those proto headers.
  606          * Because ip6_savecontrol() is going to parse the mbuf to
  607          * search for data to be passed up to user-land, it wants mbuf
  608          * parameters to be unchanged.
  609          * XXX: the call of ip6_savecontrol() has been obsoleted based on
  610          * latest version of the advanced API (20020110).
  611          */
  612         drop_hdrlen = off0 + off;
  613 
  614         /*
  615          * Locate pcb for segment.
  616          */
  617         INP_INFO_WLOCK(&tcbinfo);
  618         headlocked = 1;
  619 findpcb:
  620         KASSERT(headlocked, ("tcp_input: findpcb: head not locked"));
  621 #ifdef IPFIREWALL_FORWARD
  622         /* Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain. */
  623         fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
  624 
  625         if (fwd_tag != NULL && isipv6 == 0) {   /* IPv6 support is not yet */
  626                 struct sockaddr_in *next_hop;
  627 
  628                 next_hop = (struct sockaddr_in *)(fwd_tag+1);
  629                 /*
  630                  * Transparently forwarded. Pretend to be the destination.
  631                  * already got one like this?
  632                  */
  633                 inp = in_pcblookup_hash(&tcbinfo,
  634                                         ip->ip_src, th->th_sport,
  635                                         ip->ip_dst, th->th_dport,
  636                                         0, m->m_pkthdr.rcvif);
  637                 if (!inp) {
  638                         /* It's new.  Try to find the ambushing socket. */
  639                         inp = in_pcblookup_hash(&tcbinfo,
  640                                                 ip->ip_src, th->th_sport,
  641                                                 next_hop->sin_addr,
  642                                                 next_hop->sin_port ?
  643                                                     ntohs(next_hop->sin_port) :
  644                                                     th->th_dport,
  645                                                 1, m->m_pkthdr.rcvif);
  646                 }
  647                 /* Remove the tag from the packet.  We don't need it anymore. */
  648                 m_tag_delete(m, fwd_tag);
  649         } else {
  650 #endif /* IPFIREWALL_FORWARD */
  651                 if (isipv6) {
  652 #ifdef INET6
  653                         inp = in6_pcblookup_hash(&tcbinfo,
  654                                                  &ip6->ip6_src, th->th_sport,
  655                                                  &ip6->ip6_dst, th->th_dport,
  656                                                  1, m->m_pkthdr.rcvif);
  657 #endif
  658                 } else
  659                         inp = in_pcblookup_hash(&tcbinfo,
  660                                                 ip->ip_src, th->th_sport,
  661                                                 ip->ip_dst, th->th_dport,
  662                                                 1, m->m_pkthdr.rcvif);
  663 #ifdef IPFIREWALL_FORWARD
  664         }
  665 #endif /* IPFIREWALL_FORWARD */
  666 
  667 #if defined(IPSEC) || defined(FAST_IPSEC)
  668 #ifdef INET6
  669         if (isipv6) {
  670                 if (inp != NULL && ipsec6_in_reject(m, inp)) {
  671 #ifdef IPSEC
  672                         ipsec6stat.in_polvio++;
  673 #endif
  674                         goto drop;
  675                 }
  676         } else
  677 #endif /* INET6 */
  678         if (inp != NULL && ipsec4_in_reject(m, inp)) {
  679 #ifdef IPSEC
  680                 ipsecstat.in_polvio++;
  681 #endif
  682                 goto drop;
  683         }
  684 #endif /*IPSEC || FAST_IPSEC*/
  685 
  686         /*
  687          * If the state is CLOSED (i.e., TCB does not exist) then
  688          * all data in the incoming segment is discarded.
  689          * If the TCB exists but is in CLOSED state, it is embryonic,
  690          * but should either do a listen or a connect soon.
  691          */
  692         if (inp == NULL) {
  693                 if (log_in_vain) {
  694 #ifdef INET6
  695                         char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
  696 #else
  697                         char dbuf[4*sizeof "123"], sbuf[4*sizeof "123"];
  698 #endif
  699 
  700                         if (isipv6) {
  701 #ifdef INET6
  702                                 strcpy(dbuf, "[");
  703                                 strcpy(sbuf, "[");
  704                                 strcat(dbuf, ip6_sprintf(&ip6->ip6_dst));
  705                                 strcat(sbuf, ip6_sprintf(&ip6->ip6_src));
  706                                 strcat(dbuf, "]");
  707                                 strcat(sbuf, "]");
  708 #endif
  709                         } else {
  710                                 strcpy(dbuf, inet_ntoa(ip->ip_dst));
  711                                 strcpy(sbuf, inet_ntoa(ip->ip_src));
  712                         }
  713                         switch (log_in_vain) {
  714                         case 1:
  715                                 if ((thflags & TH_SYN) == 0)
  716                                         break;
  717                                 /* FALLTHROUGH */
  718                         case 2:
  719                                 log(LOG_INFO,
  720                                     "Connection attempt to TCP %s:%d "
  721                                     "from %s:%d flags:0x%02x\n",
  722                                     dbuf, ntohs(th->th_dport), sbuf,
  723                                     ntohs(th->th_sport), thflags);
  724                                 break;
  725                         default:
  726                                 break;
  727                         }
  728                 }
  729                 if (blackhole) {
  730                         switch (blackhole) {
  731                         case 1:
  732                                 if (thflags & TH_SYN)
  733                                         goto drop;
  734                                 break;
  735                         case 2:
  736                                 goto drop;
  737                         default:
  738                                 goto drop;
  739                         }
  740                 }
  741                 rstreason = BANDLIM_RST_CLOSEDPORT;
  742                 goto dropwithreset;
  743         }
  744         INP_LOCK(inp);
  745         if (inp->inp_vflag & INP_TIMEWAIT) {
  746                 /*
  747                  * The only option of relevance is TOF_CC, and only if
  748                  * present in a SYN segment.  See tcp_timewait().
  749                  */
  750                 if (thflags & TH_SYN)
  751                         tcp_dooptions((struct tcpcb *)NULL, &to, optp, optlen, 1, th);
  752                 if (tcp_timewait((struct tcptw *)inp->inp_ppcb,
  753                     &to, th, m, tlen))
  754                         goto findpcb;
  755                 /*
  756                  * tcp_timewait unlocks inp.
  757                  */
  758                 INP_INFO_WUNLOCK(&tcbinfo);
  759                 return;
  760         }
  761         tp = intotcpcb(inp);
  762         if (tp == 0) {
  763                 INP_UNLOCK(inp);
  764                 rstreason = BANDLIM_RST_CLOSEDPORT;
  765                 goto dropwithreset;
  766         }
  767         if (tp->t_state == TCPS_CLOSED)
  768                 goto drop;
  769 
  770         /* Unscale the window into a 32-bit value. */
  771         if ((thflags & TH_SYN) == 0)
  772                 tiwin = th->th_win << tp->snd_scale;
  773         else
  774                 tiwin = th->th_win;
  775 
  776 #ifdef MAC
  777         INP_LOCK_ASSERT(inp);
  778         if (mac_check_inpcb_deliver(inp, m))
  779                 goto drop;
  780 #endif
  781         so = inp->inp_socket;
  782 #ifdef TCPDEBUG
  783         if (so->so_options & SO_DEBUG) {
  784                 ostate = tp->t_state;
  785                 if (isipv6)
  786                         bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
  787                 else
  788                         bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
  789                 tcp_savetcp = *th;
  790         }
  791 #endif
  792         if (so->so_options & SO_ACCEPTCONN) {
  793                 struct in_conninfo inc;
  794 
  795 #ifdef INET6
  796                 inc.inc_isipv6 = isipv6;
  797 #endif
  798                 if (isipv6) {
  799                         inc.inc6_faddr = ip6->ip6_src;
  800                         inc.inc6_laddr = ip6->ip6_dst;
  801                 } else {
  802                         inc.inc_faddr = ip->ip_src;
  803                         inc.inc_laddr = ip->ip_dst;
  804                 }
  805                 inc.inc_fport = th->th_sport;
  806                 inc.inc_lport = th->th_dport;
  807 
  808                 /*
  809                  * If the state is LISTEN then ignore segment if it contains
  810                  * a RST.  If the segment contains an ACK then it is bad and
  811                  * send a RST.  If it does not contain a SYN then it is not
  812                  * interesting; drop it.
  813                  *
  814                  * If the state is SYN_RECEIVED (syncache) and seg contains
  815                  * an ACK, but not for our SYN/ACK, send a RST.  If the seg
  816                  * contains a RST, check the sequence number to see if it
  817                  * is a valid reset segment.
  818                  */
  819                 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
  820                         if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
  821                                 if (!syncache_expand(&inc, th, &so, m)) {
  822                                         /*
  823                                          * No syncache entry, or ACK was not
  824                                          * for our SYN/ACK.  Send a RST.
  825                                          */
  826                                         tcpstat.tcps_badsyn++;
  827                                         rstreason = BANDLIM_RST_OPENPORT;
  828                                         goto dropwithreset;
  829                                 }
  830                                 if (so == NULL) {
  831                                         /*
  832                                          * Could not complete 3-way handshake,
  833                                          * connection is being closed down, and
  834                                          * syncache will free mbuf.
  835                                          */
  836                                         INP_UNLOCK(inp);
  837                                         INP_INFO_WUNLOCK(&tcbinfo);
  838                                         return;
  839                                 }
  840                                 /*
  841                                  * Socket is created in state SYN_RECEIVED.
  842                                  * Continue processing segment.
  843                                  */
  844                                 INP_UNLOCK(inp);
  845                                 inp = sotoinpcb(so);
  846                                 INP_LOCK(inp);
  847                                 tp = intotcpcb(inp);
  848                                 /*
  849                                  * This is what would have happened in
  850                                  * tcp_output() when the SYN,ACK was sent.
  851                                  */
  852                                 tp->snd_up = tp->snd_una;
  853                                 tp->snd_max = tp->snd_nxt = tp->iss + 1;
  854                                 tp->last_ack_sent = tp->rcv_nxt;
  855                                 /*
  856                                  * RFC1323: The window in SYN & SYN/ACK
  857                                  * segments is never scaled.
  858                                  */
  859                                 tp->snd_wnd = tiwin;    /* unscaled */
  860                                 goto after_listen;
  861                         }
  862                         if (thflags & TH_RST) {
  863                                 syncache_chkrst(&inc, th);
  864                                 goto drop;
  865                         }
  866                         if (thflags & TH_ACK) {
  867                                 syncache_badack(&inc);
  868                                 tcpstat.tcps_badsyn++;
  869                                 rstreason = BANDLIM_RST_OPENPORT;
  870                                 goto dropwithreset;
  871                         }
  872                         goto drop;
  873                 }
  874 
  875                 /*
  876                  * Segment's flags are (SYN) or (SYN|FIN).
  877                  */
  878 #ifdef INET6
  879                 /*
  880                  * If deprecated address is forbidden,
  881                  * we do not accept SYN to deprecated interface
  882                  * address to prevent any new inbound connection from
  883                  * getting established.
  884                  * When we do not accept SYN, we send a TCP RST,
  885                  * with deprecated source address (instead of dropping
  886                  * it).  We compromise it as it is much better for peer
  887                  * to send a RST, and RST will be the final packet
  888                  * for the exchange.
  889                  *
  890                  * If we do not forbid deprecated addresses, we accept
  891                  * the SYN packet.  RFC2462 does not suggest dropping
  892                  * SYN in this case.
  893                  * If we decipher RFC2462 5.5.4, it says like this:
  894                  * 1. use of deprecated addr with existing
  895                  *    communication is okay - "SHOULD continue to be
  896                  *    used"
  897                  * 2. use of it with new communication:
  898                  *   (2a) "SHOULD NOT be used if alternate address
  899                  *        with sufficient scope is available"
  900                  *   (2b) nothing mentioned otherwise.
  901                  * Here we fall into (2b) case as we have no choice in
  902                  * our source address selection - we must obey the peer.
  903                  *
  904                  * The wording in RFC2462 is confusing, and there are
  905                  * multiple description text for deprecated address
  906                  * handling - worse, they are not exactly the same.
  907                  * I believe 5.5.4 is the best one, so we follow 5.5.4.
  908                  */
  909                 if (isipv6 && !ip6_use_deprecated) {
  910                         struct in6_ifaddr *ia6;
  911 
  912                         if ((ia6 = ip6_getdstifaddr(m)) &&
  913                             (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
  914                                 INP_UNLOCK(inp);
  915                                 tp = NULL;
  916                                 rstreason = BANDLIM_RST_OPENPORT;
  917                                 goto dropwithreset;
  918                         }
  919                 }
  920 #endif
  921                 /*
  922                  * If it is from this socket, drop it, it must be forged.
  923                  * Don't bother responding if the destination was a broadcast.
  924                  */
  925                 if (th->th_dport == th->th_sport) {
  926                         if (isipv6) {
  927                                 if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
  928                                                        &ip6->ip6_src))
  929                                         goto drop;
  930                         } else {
  931                                 if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
  932                                         goto drop;
  933                         }
  934                 }
  935                 /*
  936                  * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
  937                  *
  938                  * Note that it is quite possible to receive unicast
  939                  * link-layer packets with a broadcast IP address. Use
  940                  * in_broadcast() to find them.
  941                  */
  942                 if (m->m_flags & (M_BCAST|M_MCAST))
  943                         goto drop;
  944                 if (isipv6) {
  945                         if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
  946                             IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
  947                                 goto drop;
  948                 } else {
  949                         if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
  950                             IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
  951                             ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
  952                             in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
  953                                 goto drop;
  954                 }
  955                 /*
  956                  * SYN appears to be valid; create compressed TCP state
  957                  * for syncache, or perform t/tcp connection.
  958                  */
  959                 if (so->so_qlen <= so->so_qlimit) {
  960 #ifdef TCPDEBUG
  961                         if (so->so_options & SO_DEBUG)
  962                                 tcp_trace(TA_INPUT, ostate, tp,
  963                                     (void *)tcp_saveipgen, &tcp_savetcp, 0);
  964 #endif
  965                         tcp_dooptions(tp, &to, optp, optlen, 1, th);
  966                         if (!syncache_add(&inc, &to, th, &so, m))
  967                                 goto drop;
  968                         if (so == NULL) {
  969                                 /*
  970                                  * Entry added to syncache, mbuf used to
  971                                  * send SYN,ACK packet.
  972                                  */
  973                                 KASSERT(headlocked, ("headlocked"));
  974                                 INP_UNLOCK(inp);
  975                                 INP_INFO_WUNLOCK(&tcbinfo);
  976                                 return;
  977                         }
  978                         /*
  979                          * Segment passed TAO tests.
  980                          */
  981                         INP_UNLOCK(inp);
  982                         inp = sotoinpcb(so);
  983                         INP_LOCK(inp);
  984                         tp = intotcpcb(inp);
  985                         tp->snd_wnd = tiwin;
  986                         tp->t_starttime = ticks;
  987                         tp->t_state = TCPS_ESTABLISHED;
  988 
  989                         /*
  990                          * T/TCP logic:
  991                          * If there is a FIN or if there is data, then
  992                          * delay SYN,ACK(SYN) in the hope of piggy-backing
  993                          * it on a response segment.  Otherwise must send
  994                          * ACK now in case the other side is slow starting.
  995                          */
  996                         if (thflags & TH_FIN || tlen != 0)
  997                                 tp->t_flags |= (TF_DELACK | TF_NEEDSYN);
  998                         else
  999                                 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
 1000                         tcpstat.tcps_connects++;
 1001                         soisconnected(so);
 1002                         goto trimthenstep6;
 1003                 }
 1004                 goto drop;
 1005         }
 1006 after_listen:
 1007         KASSERT(headlocked, ("tcp_input: after_listen: head not locked"));
 1008         INP_LOCK_ASSERT(inp);
 1009 
 1010         /* XXX temp debugging */
 1011         /* should not happen - syncache should pick up these connections */
 1012         if (tp->t_state == TCPS_LISTEN)
 1013                 panic("tcp_input: TCPS_LISTEN");
 1014 
 1015         /*
 1016          * This is the second part of the MSS DoS prevention code (after
 1017          * minmss on the sending side) and it deals with too many too small
 1018          * tcp packets in a too short timeframe (1 second).
 1019          *
 1020          * For every full second we count the number of received packets
 1021          * and bytes. If we get a lot of packets per second for this connection
 1022          * (tcp_minmssoverload) we take a closer look at it and compute the
 1023          * average packet size for the past second. If that is less than
 1024          * tcp_minmss we get too many packets with very small payload which
 1025          * is not good and burdens our system (and every packet generates
 1026          * a wakeup to the process connected to our socket). We can reasonable
 1027          * expect this to be small packet DoS attack to exhaust our CPU
 1028          * cycles.
 1029          *
 1030          * Care has to be taken for the minimum packet overload value. This
 1031          * value defines the minimum number of packets per second before we
 1032          * start to worry. This must not be too low to avoid killing for
 1033          * example interactive connections with many small packets like
 1034          * telnet or SSH.
 1035          *
 1036          * Setting either tcp_minmssoverload or tcp_minmss to "" disables
 1037          * this check.
 1038          *
 1039          * Account for packet if payload packet, skip over ACK, etc.
 1040          */
 1041         if (tcp_minmss && tcp_minmssoverload &&
 1042             tp->t_state == TCPS_ESTABLISHED && tlen > 0) {
 1043                 if (tp->rcv_second > ticks) {
 1044                         tp->rcv_pps++;
 1045                         tp->rcv_byps += tlen + off;
 1046                         if (tp->rcv_pps > tcp_minmssoverload) {
 1047                                 if ((tp->rcv_byps / tp->rcv_pps) < tcp_minmss) {
 1048                                         printf("too many small tcp packets from "
 1049                                                "%s:%u, av. %lubyte/packet, "
 1050                                                "dropping connection\n",
 1051 #ifdef INET6
 1052                                                 isipv6 ?
 1053                                                 ip6_sprintf(&inp->inp_inc.inc6_faddr) :
 1054 #endif
 1055                                                 inet_ntoa(inp->inp_inc.inc_faddr),
 1056                                                 inp->inp_inc.inc_fport,
 1057                                                 tp->rcv_byps / tp->rcv_pps);
 1058                                         tp = tcp_drop(tp, ECONNRESET);
 1059                                         tcpstat.tcps_minmssdrops++;
 1060                                         goto drop;
 1061                                 }
 1062                         }
 1063                 } else {
 1064                         tp->rcv_second = ticks + hz;
 1065                         tp->rcv_pps = 1;
 1066                         tp->rcv_byps = tlen + off;
 1067                 }
 1068         }
 1069 
 1070         /*
 1071          * Segment received on connection.
 1072          * Reset idle time and keep-alive timer.
 1073          */
 1074         tp->t_rcvtime = ticks;
 1075         if (TCPS_HAVEESTABLISHED(tp->t_state))
 1076                 callout_reset(tp->tt_keep, tcp_keepidle, tcp_timer_keep, tp);
 1077 
 1078         /*
 1079          * Process options only when we get SYN/ACK back. The SYN case
 1080          * for incoming connections is handled in tcp_syncache.
 1081          * XXX this is traditional behavior, may need to be cleaned up.
 1082          */
 1083         tcp_dooptions(tp, &to, optp, optlen, thflags & TH_SYN, th);
 1084         if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
 1085                 if (to.to_flags & TOF_SCALE) {
 1086                         tp->t_flags |= TF_RCVD_SCALE;
 1087                         tp->requested_s_scale = to.to_requested_s_scale;
 1088                 }
 1089                 if (to.to_flags & TOF_TS) {
 1090                         tp->t_flags |= TF_RCVD_TSTMP;
 1091                         tp->ts_recent = to.to_tsval;
 1092                         tp->ts_recent_age = ticks;
 1093                 }
 1094                 if (to.to_flags & (TOF_CC|TOF_CCNEW))
 1095                         tp->t_flags |= TF_RCVD_CC;
 1096                 if (to.to_flags & TOF_MSS)
 1097                         tcp_mss(tp, to.to_mss);
 1098                 if (tp->sack_enable) {
 1099                         if (!(to.to_flags & TOF_SACK))
 1100                                 tp->sack_enable = 0;
 1101                         else
 1102                                 tp->t_flags |= TF_SACK_PERMIT;
 1103                 }
 1104 
 1105         }
 1106 
 1107         if (tp->sack_enable) {
 1108                 /* Delete stale (cumulatively acked) SACK holes */
 1109                 tcp_del_sackholes(tp, th);
 1110         }
 1111 
 1112         /*
 1113          * Header prediction: check for the two common cases
 1114          * of a uni-directional data xfer.  If the packet has
 1115          * no control flags, is in-sequence, the window didn't
 1116          * change and we're not retransmitting, it's a
 1117          * candidate.  If the length is zero and the ack moved
 1118          * forward, we're the sender side of the xfer.  Just
 1119          * free the data acked & wake any higher level process
 1120          * that was blocked waiting for space.  If the length
 1121          * is non-zero and the ack didn't move, we're the
 1122          * receiver side.  If we're getting packets in-order
 1123          * (the reassembly queue is empty), add the data to
 1124          * the socket buffer and note that we need a delayed ack.
 1125          * Make sure that the hidden state-flags are also off.
 1126          * Since we check for TCPS_ESTABLISHED above, it can only
 1127          * be TH_NEEDSYN.
 1128          */
 1129         if (tp->t_state == TCPS_ESTABLISHED &&
 1130             (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
 1131             ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
 1132             ((to.to_flags & TOF_TS) == 0 ||
 1133              TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
 1134             /*
 1135              * Using the CC option is compulsory if once started:
 1136              *   the segment is OK if no T/TCP was negotiated or
 1137              *   if the segment has a CC option equal to CCrecv
 1138              */
 1139             ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) != (TF_REQ_CC|TF_RCVD_CC) ||
 1140              ((to.to_flags & TOF_CC) != 0 && to.to_cc == tp->cc_recv)) &&
 1141             th->th_seq == tp->rcv_nxt &&
 1142             tiwin && tiwin == tp->snd_wnd &&
 1143             tp->snd_nxt == tp->snd_max) {
 1144 
 1145                 /*
 1146                  * If last ACK falls within this segment's sequence numbers,
 1147                  * record the timestamp.
 1148                  * NOTE that the test is modified according to the latest
 1149                  * proposal of the tcplw@cray.com list (Braden 1993/04/26).
 1150                  */
 1151                 if ((to.to_flags & TOF_TS) != 0 &&
 1152                     SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
 1153                         tp->ts_recent_age = ticks;
 1154                         tp->ts_recent = to.to_tsval;
 1155                 }
 1156 
 1157                 if (tlen == 0) {
 1158                         if (SEQ_GT(th->th_ack, tp->snd_una) &&
 1159                             SEQ_LEQ(th->th_ack, tp->snd_max) &&
 1160                             tp->snd_cwnd >= tp->snd_wnd &&
 1161                             ((!tcp_do_newreno && !tp->sack_enable &&
 1162                               tp->t_dupacks < tcprexmtthresh) ||
 1163                              ((tcp_do_newreno || tp->sack_enable) &&
 1164                               !IN_FASTRECOVERY(tp)))) {
 1165                                 KASSERT(headlocked, ("headlocked"));
 1166                                 INP_INFO_WUNLOCK(&tcbinfo);
 1167                                 headlocked = 0;
 1168                                 /*
 1169                                  * this is a pure ack for outstanding data.
 1170                                  */
 1171                                 ++tcpstat.tcps_predack;
 1172                                 /*
 1173                                  * "bad retransmit" recovery
 1174                                  */
 1175                                 if (tp->t_rxtshift == 1 &&
 1176                                     ticks < tp->t_badrxtwin) {
 1177                                         ++tcpstat.tcps_sndrexmitbad;
 1178                                         tp->snd_cwnd = tp->snd_cwnd_prev;
 1179                                         tp->snd_ssthresh =
 1180                                             tp->snd_ssthresh_prev;
 1181                                         tp->snd_recover = tp->snd_recover_prev;
 1182                                         if (tp->t_flags & TF_WASFRECOVERY)
 1183                                             ENTER_FASTRECOVERY(tp);
 1184                                         tp->snd_nxt = tp->snd_max;
 1185                                         tp->t_badrxtwin = 0;
 1186                                 }
 1187 
 1188                                 /*
 1189                                  * Recalculate the transmit timer / rtt.
 1190                                  *
 1191                                  * Some boxes send broken timestamp replies
 1192                                  * during the SYN+ACK phase, ignore
 1193                                  * timestamps of 0 or we could calculate a
 1194                                  * huge RTT and blow up the retransmit timer.
 1195                                  */
 1196                                 if ((to.to_flags & TOF_TS) != 0 &&
 1197                                     to.to_tsecr) {
 1198                                         tcp_xmit_timer(tp,
 1199                                             ticks - to.to_tsecr + 1);
 1200                                 } else if (tp->t_rtttime &&
 1201                                             SEQ_GT(th->th_ack, tp->t_rtseq)) {
 1202                                         tcp_xmit_timer(tp,
 1203                                                         ticks - tp->t_rtttime);
 1204                                 }
 1205                                 tcp_xmit_bandwidth_limit(tp, th->th_ack);
 1206                                 acked = th->th_ack - tp->snd_una;
 1207                                 tcpstat.tcps_rcvackpack++;
 1208                                 tcpstat.tcps_rcvackbyte += acked;
 1209                                 sbdrop(&so->so_snd, acked);
 1210                                 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
 1211                                     SEQ_LEQ(th->th_ack, tp->snd_recover))
 1212                                         tp->snd_recover = th->th_ack - 1;
 1213                                 tp->snd_una = th->th_ack;
 1214                                 /*
 1215                                  * pull snd_wl2 up to prevent seq wrap relative
 1216                                  * to th_ack.
 1217                                  */
 1218                                 tp->snd_wl2 = th->th_ack;
 1219                                 tp->t_dupacks = 0;
 1220                                 m_freem(m);
 1221                                 ND6_HINT(tp); /* some progress has been done */
 1222 
 1223                                 /*
 1224                                  * If all outstanding data are acked, stop
 1225                                  * retransmit timer, otherwise restart timer
 1226                                  * using current (possibly backed-off) value.
 1227                                  * If process is waiting for space,
 1228                                  * wakeup/selwakeup/signal.  If data
 1229                                  * are ready to send, let tcp_output
 1230                                  * decide between more output or persist.
 1231 
 1232 #ifdef TCPDEBUG
 1233                                 if (so->so_options & SO_DEBUG)
 1234                                         tcp_trace(TA_INPUT, ostate, tp,
 1235                                             (void *)tcp_saveipgen,
 1236                                             &tcp_savetcp, 0);
 1237 #endif
 1238                                  */
 1239                                 if (tp->snd_una == tp->snd_max)
 1240                                         callout_stop(tp->tt_rexmt);
 1241                                 else if (!callout_active(tp->tt_persist))
 1242                                         callout_reset(tp->tt_rexmt,
 1243                                                       tp->t_rxtcur,
 1244                                                       tcp_timer_rexmt, tp);
 1245 
 1246                                 sowwakeup(so);
 1247                                 if (so->so_snd.sb_cc)
 1248                                         (void) tcp_output(tp);
 1249                                 goto check_delack;
 1250                         }
 1251                 } else if (th->th_ack == tp->snd_una &&
 1252                     LIST_EMPTY(&tp->t_segq) &&
 1253                     tlen <= sbspace(&so->so_rcv)) {
 1254                         KASSERT(headlocked, ("headlocked"));
 1255                         INP_INFO_WUNLOCK(&tcbinfo);
 1256                         headlocked = 0;
 1257                         /*
 1258                          * this is a pure, in-sequence data packet
 1259                          * with nothing on the reassembly queue and
 1260                          * we have enough buffer space to take it.
 1261                          */
 1262                         /* Clean receiver SACK report if present */
 1263                         if (tp->sack_enable && tp->rcv_numsacks)
 1264                                 tcp_clean_sackreport(tp);
 1265                         ++tcpstat.tcps_preddat;
 1266                         tp->rcv_nxt += tlen;
 1267                         /*
 1268                          * Pull snd_wl1 up to prevent seq wrap relative to
 1269                          * th_seq.
 1270                          */
 1271                         tp->snd_wl1 = th->th_seq;
 1272                         /*
 1273                          * Pull rcv_up up to prevent seq wrap relative to
 1274                          * rcv_nxt.
 1275                          */
 1276                         tp->rcv_up = tp->rcv_nxt;
 1277                         tcpstat.tcps_rcvpack++;
 1278                         tcpstat.tcps_rcvbyte += tlen;
 1279                         ND6_HINT(tp);   /* some progress has been done */
 1280                         /*
 1281 #ifdef TCPDEBUG
 1282                         if (so->so_options & SO_DEBUG)
 1283                                 tcp_trace(TA_INPUT, ostate, tp,
 1284                                     (void *)tcp_saveipgen, &tcp_savetcp, 0);
 1285 #endif
 1286                          * Add data to socket buffer.
 1287                          */
 1288                         SOCKBUF_LOCK(&so->so_rcv);
 1289                         if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
 1290                                 m_freem(m);
 1291                         } else {
 1292                                 m_adj(m, drop_hdrlen);  /* delayed header drop */
 1293                                 sbappendstream_locked(&so->so_rcv, m);
 1294                         }
 1295                         sorwakeup_locked(so);
 1296                         if (DELAY_ACK(tp)) {
 1297                                 tp->t_flags |= TF_DELACK;
 1298                         } else {
 1299                                 tp->t_flags |= TF_ACKNOW;
 1300                                 tcp_output(tp);
 1301                         }
 1302                         goto check_delack;
 1303                 }
 1304         }
 1305 
 1306         /*
 1307          * Calculate amount of space in receive window,
 1308          * and then do TCP input processing.
 1309          * Receive window is amount of space in rcv queue,
 1310          * but not less than advertised window.
 1311          */
 1312         { int win;
 1313 
 1314         win = sbspace(&so->so_rcv);
 1315         if (win < 0)
 1316                 win = 0;
 1317         tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
 1318         }
 1319 
 1320         switch (tp->t_state) {
 1321 
 1322         /*
 1323          * If the state is SYN_RECEIVED:
 1324          *      if seg contains an ACK, but not for our SYN/ACK, send a RST.
 1325          */
 1326         case TCPS_SYN_RECEIVED:
 1327                 if ((thflags & TH_ACK) &&
 1328                     (SEQ_LEQ(th->th_ack, tp->snd_una) ||
 1329                      SEQ_GT(th->th_ack, tp->snd_max))) {
 1330                                 rstreason = BANDLIM_RST_OPENPORT;
 1331                                 goto dropwithreset;
 1332                 }
 1333                 break;
 1334 
 1335         /*
 1336          * If the state is SYN_SENT:
 1337          *      if seg contains an ACK, but not for our SYN, drop the input.
 1338          *      if seg contains a RST, then drop the connection.
 1339          *      if seg does not contain SYN, then drop it.
 1340          * Otherwise this is an acceptable SYN segment
 1341          *      initialize tp->rcv_nxt and tp->irs
 1342          *      if seg contains ack then advance tp->snd_una
 1343          *      if SYN has been acked change to ESTABLISHED else SYN_RCVD state
 1344          *      arrange for segment to be acked (eventually)
 1345          *      continue processing rest of data/controls, beginning with URG
 1346          */
 1347         case TCPS_SYN_SENT:
 1348                 if (tcp_do_rfc1644)
 1349                         tcp_hc_gettao(&inp->inp_inc, &tao);
 1350 
 1351                 if ((thflags & TH_ACK) &&
 1352                     (SEQ_LEQ(th->th_ack, tp->iss) ||
 1353                      SEQ_GT(th->th_ack, tp->snd_max))) {
 1354                         /*
 1355                          * If we have a cached CCsent for the remote host,
 1356                          * hence we haven't just crashed and restarted,
 1357                          * do not send a RST.  This may be a retransmission
 1358                          * from the other side after our earlier ACK was lost.
 1359                          * Our new SYN, when it arrives, will serve as the
 1360                          * needed ACK.
 1361                          */
 1362                         if (tao.tao_ccsent != 0)
 1363                                 goto drop;
 1364                         else {
 1365                                 rstreason = BANDLIM_UNLIMITED;
 1366                                 goto dropwithreset;
 1367                         }
 1368                 }
 1369                 if (thflags & TH_RST) {
 1370                         if (thflags & TH_ACK)
 1371                                 tp = tcp_drop(tp, ECONNREFUSED);
 1372                         goto drop;
 1373                 }
 1374                 if ((thflags & TH_SYN) == 0)
 1375                         goto drop;
 1376                 tp->snd_wnd = th->th_win;       /* initial send window */
 1377                 tp->cc_recv = to.to_cc;         /* foreign CC */
 1378 
 1379                 tp->irs = th->th_seq;
 1380                 tcp_rcvseqinit(tp);
 1381                 if (thflags & TH_ACK) {
 1382                         /*
 1383                          * Our SYN was acked.  If segment contains CC.ECHO
 1384                          * option, check it to make sure this segment really
 1385                          * matches our SYN.  If not, just drop it as old
 1386                          * duplicate, but send an RST if we're still playing
 1387                          * by the old rules.  If no CC.ECHO option, make sure
 1388                          * we don't get fooled into using T/TCP.
 1389                          */
 1390                         if (to.to_flags & TOF_CCECHO) {
 1391                                 if (tp->cc_send != to.to_ccecho) {
 1392                                         if (tao.tao_ccsent != 0)
 1393                                                 goto drop;
 1394                                         else {
 1395                                                 rstreason = BANDLIM_UNLIMITED;
 1396                                                 goto dropwithreset;
 1397                                         }
 1398                                 }
 1399                         } else
 1400                                 tp->t_flags &= ~TF_RCVD_CC;
 1401                         tcpstat.tcps_connects++;
 1402                         soisconnected(so);
 1403 #ifdef MAC
 1404                         SOCK_LOCK(so);
 1405                         mac_set_socket_peer_from_mbuf(m, so);
 1406                         SOCK_UNLOCK(so);
 1407 #endif
 1408                         /* Do window scaling on this connection? */
 1409                         if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
 1410                                 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
 1411                                 tp->snd_scale = tp->requested_s_scale;
 1412                                 tp->rcv_scale = tp->request_r_scale;
 1413                         }
 1414                         /* Segment is acceptable, update cache if undefined. */
 1415                         if (tao.tao_ccsent == 0 && tcp_do_rfc1644)
 1416                                 tcp_hc_updatetao(&inp->inp_inc, TCP_HC_TAO_CCSENT, to.to_ccecho, 0);
 1417 
 1418                         tp->rcv_adv += tp->rcv_wnd;
 1419                         tp->snd_una++;          /* SYN is acked */
 1420                         /*
 1421                          * If there's data, delay ACK; if there's also a FIN
 1422                          * ACKNOW will be turned on later.
 1423                          */
 1424                         if (DELAY_ACK(tp) && tlen != 0)
 1425                                 callout_reset(tp->tt_delack, tcp_delacktime,
 1426                                     tcp_timer_delack, tp);
 1427                         else
 1428                                 tp->t_flags |= TF_ACKNOW;
 1429                         /*
 1430                          * Received <SYN,ACK> in SYN_SENT[*] state.
 1431                          * Transitions:
 1432                          *      SYN_SENT  --> ESTABLISHED
 1433                          *      SYN_SENT* --> FIN_WAIT_1
 1434                          */
 1435                         tp->t_starttime = ticks;
 1436                         if (tp->t_flags & TF_NEEDFIN) {
 1437                                 tp->t_state = TCPS_FIN_WAIT_1;
 1438                                 tp->t_flags &= ~TF_NEEDFIN;
 1439                                 thflags &= ~TH_SYN;
 1440                         } else {
 1441                                 tp->t_state = TCPS_ESTABLISHED;
 1442                                 callout_reset(tp->tt_keep, tcp_keepidle,
 1443                                               tcp_timer_keep, tp);
 1444                         }
 1445                 } else {
 1446                         /*
 1447                          * Received initial SYN in SYN-SENT[*] state =>
 1448                          * simultaneous open.  If segment contains CC option
 1449                          * and there is a cached CC, apply TAO test.
 1450                          * If it succeeds, connection is * half-synchronized.
 1451                          * Otherwise, do 3-way handshake:
 1452                          *        SYN-SENT -> SYN-RECEIVED
 1453                          *        SYN-SENT* -> SYN-RECEIVED*
 1454                          * If there was no CC option, clear cached CC value.
 1455                          */
 1456                         tp->t_flags |= TF_ACKNOW;
 1457                         callout_stop(tp->tt_rexmt);
 1458                         if (to.to_flags & TOF_CC) {
 1459                                 if (tao.tao_cc != 0 &&
 1460                                     CC_GT(to.to_cc, tao.tao_cc)) {
 1461                                         /*
 1462                                          * update cache and make transition:
 1463                                          *        SYN-SENT -> ESTABLISHED*
 1464                                          *        SYN-SENT* -> FIN-WAIT-1*
 1465                                          */
 1466                                         tao.tao_cc = to.to_cc;
 1467                                         tcp_hc_updatetao(&inp->inp_inc,
 1468                                                 TCP_HC_TAO_CC, to.to_cc, 0);
 1469                                         tp->t_starttime = ticks;
 1470                                         if (tp->t_flags & TF_NEEDFIN) {
 1471                                                 tp->t_state = TCPS_FIN_WAIT_1;
 1472                                                 tp->t_flags &= ~TF_NEEDFIN;
 1473                                         } else {
 1474                                                 tp->t_state = TCPS_ESTABLISHED;
 1475                                                 callout_reset(tp->tt_keep,
 1476                                                               tcp_keepidle,
 1477                                                               tcp_timer_keep,
 1478                                                               tp);
 1479                                         }
 1480                                         tp->t_flags |= TF_NEEDSYN;
 1481                                 } else
 1482                                         tp->t_state = TCPS_SYN_RECEIVED;
 1483                         } else {
 1484                                 if (tcp_do_rfc1644) {
 1485                                         /* CC.NEW or no option => invalidate cache */
 1486                                         tao.tao_cc = 0;
 1487                                         tcp_hc_updatetao(&inp->inp_inc,
 1488                                                 TCP_HC_TAO_CC, to.to_cc, 0);
 1489                                 }
 1490                                 tp->t_state = TCPS_SYN_RECEIVED;
 1491                         }
 1492                 }
 1493 
 1494 trimthenstep6:
 1495                 KASSERT(headlocked, ("tcp_input: trimthenstep6: head not "
 1496                     "locked"));
 1497                 INP_LOCK_ASSERT(inp);
 1498 
 1499                 /*
 1500                  * Advance th->th_seq to correspond to first data byte.
 1501                  * If data, trim to stay within window,
 1502                  * dropping FIN if necessary.
 1503                  */
 1504                 th->th_seq++;
 1505                 if (tlen > tp->rcv_wnd) {
 1506                         todrop = tlen - tp->rcv_wnd;
 1507                         m_adj(m, -todrop);
 1508                         tlen = tp->rcv_wnd;
 1509                         thflags &= ~TH_FIN;
 1510                         tcpstat.tcps_rcvpackafterwin++;
 1511                         tcpstat.tcps_rcvbyteafterwin += todrop;
 1512                 }
 1513                 tp->snd_wl1 = th->th_seq - 1;
 1514                 tp->rcv_up = th->th_seq;
 1515                 /*
 1516                  * Client side of transaction: already sent SYN and data.
 1517                  * If the remote host used T/TCP to validate the SYN,
 1518                  * our data will be ACK'd; if so, enter normal data segment
 1519                  * processing in the middle of step 5, ack processing.
 1520                  * Otherwise, goto step 6.
 1521                  */
 1522                 if (thflags & TH_ACK)
 1523                         goto process_ACK;
 1524 
 1525                 goto step6;
 1526 
 1527         /*
 1528          * If the state is LAST_ACK or CLOSING or TIME_WAIT:
 1529          *      if segment contains a SYN and CC [not CC.NEW] option:
 1530          *              if state == TIME_WAIT and connection duration > MSL,
 1531          *                  drop packet and send RST;
 1532          *
 1533          *              if SEG.CC > CCrecv then is new SYN, and can implicitly
 1534          *                  ack the FIN (and data) in retransmission queue.
 1535          *                  Complete close and delete TCPCB.  Then reprocess
 1536          *                  segment, hoping to find new TCPCB in LISTEN state;
 1537          *
 1538          *              else must be old SYN; drop it.
 1539          *      else do normal processing.
 1540          */
 1541         case TCPS_LAST_ACK:
 1542         case TCPS_CLOSING:
 1543         case TCPS_TIME_WAIT:
 1544                 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
 1545                 if ((thflags & TH_SYN) &&
 1546                     (to.to_flags & TOF_CC) && tp->cc_recv != 0) {
 1547                         if (tp->t_state == TCPS_TIME_WAIT &&
 1548                                         (ticks - tp->t_starttime) > tcp_msl) {
 1549                                 rstreason = BANDLIM_UNLIMITED;
 1550                                 goto dropwithreset;
 1551                         }
 1552                         if (CC_GT(to.to_cc, tp->cc_recv)) {
 1553                                 tp = tcp_close(tp);
 1554                                 goto findpcb;
 1555                         }
 1556                         else
 1557                                 goto drop;
 1558                 }
 1559                 break;  /* continue normal processing */
 1560         }
 1561 
 1562         /*
 1563          * States other than LISTEN or SYN_SENT.
 1564          * First check the RST flag and sequence number since reset segments
 1565          * are exempt from the timestamp and connection count tests.  This
 1566          * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
 1567          * below which allowed reset segments in half the sequence space
 1568          * to fall though and be processed (which gives forged reset
 1569          * segments with a random sequence number a 50 percent chance of
 1570          * killing a connection).
 1571          * Then check timestamp, if present.
 1572          * Then check the connection count, if present.
 1573          * Then check that at least some bytes of segment are within
 1574          * receive window.  If segment begins before rcv_nxt,
 1575          * drop leading data (and SYN); if nothing left, just ack.
 1576          *
 1577          *
 1578          * If the RST bit is set, check the sequence number to see
 1579          * if this is a valid reset segment.
 1580          * RFC 793 page 37:
 1581          *   In all states except SYN-SENT, all reset (RST) segments
 1582          *   are validated by checking their SEQ-fields.  A reset is
 1583          *   valid if its sequence number is in the window.
 1584          * Note: this does not take into account delayed ACKs, so
 1585          *   we should test against last_ack_sent instead of rcv_nxt.
 1586          *   The sequence number in the reset segment is normally an
 1587          *   echo of our outgoing acknowlegement numbers, but some hosts
 1588          *   send a reset with the sequence number at the rightmost edge
 1589          *   of our receive window, and we have to handle this case.
 1590          * Note 2: Paul Watson's paper "Slipping in the Window" has shown
 1591          *   that brute force RST attacks are possible.  To combat this,
 1592          *   we use a much stricter check while in the ESTABLISHED state,
 1593          *   only accepting RSTs where the sequence number is equal to
 1594          *   last_ack_sent.  In all other states (the states in which a
 1595          *   RST is more likely), the more permissive check is used.
 1596          * If we have multiple segments in flight, the intial reset
 1597          * segment sequence numbers will be to the left of last_ack_sent,
 1598          * but they will eventually catch up.
 1599          * In any case, it never made sense to trim reset segments to
 1600          * fit the receive window since RFC 1122 says:
 1601          *   4.2.2.12  RST Segment: RFC-793 Section 3.4
 1602          *
 1603          *    A TCP SHOULD allow a received RST segment to include data.
 1604          *
 1605          *    DISCUSSION
 1606          *         It has been suggested that a RST segment could contain
 1607          *         ASCII text that encoded and explained the cause of the
 1608          *         RST.  No standard has yet been established for such
 1609          *         data.
 1610          *
 1611          * If the reset segment passes the sequence number test examine
 1612          * the state:
 1613          *    SYN_RECEIVED STATE:
 1614          *      If passive open, return to LISTEN state.
 1615          *      If active open, inform user that connection was refused.
 1616          *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
 1617          *      Inform user that connection was reset, and close tcb.
 1618          *    CLOSING, LAST_ACK STATES:
 1619          *      Close the tcb.
 1620          *    TIME_WAIT STATE:
 1621          *      Drop the segment - see Stevens, vol. 2, p. 964 and
 1622          *      RFC 1337.
 1623          */
 1624         if (thflags & TH_RST) {
 1625                 if ((SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
 1626                     SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
 1627                     (tp->rcv_wnd == 0 && tp->last_ack_sent == th->th_seq)) {
 1628                         switch (tp->t_state) {
 1629 
 1630                         case TCPS_SYN_RECEIVED:
 1631                                 so->so_error = ECONNREFUSED;
 1632                                 goto close;
 1633 
 1634                         case TCPS_ESTABLISHED:
 1635                                 if (tp->last_ack_sent != th->th_seq &&
 1636                                     tcp_insecure_rst == 0) {
 1637                                         tcpstat.tcps_badrst++;
 1638                                         goto drop;
 1639                                 }
 1640                         case TCPS_FIN_WAIT_1:
 1641                         case TCPS_FIN_WAIT_2:
 1642                         case TCPS_CLOSE_WAIT:
 1643                                 so->so_error = ECONNRESET;
 1644                         close:
 1645                                 tp->t_state = TCPS_CLOSED;
 1646                                 tcpstat.tcps_drops++;
 1647                                 tp = tcp_close(tp);
 1648                                 break;
 1649 
 1650                         case TCPS_CLOSING:
 1651                         case TCPS_LAST_ACK:
 1652                                 tp = tcp_close(tp);
 1653                                 break;
 1654 
 1655                         case TCPS_TIME_WAIT:
 1656                                 KASSERT(tp->t_state != TCPS_TIME_WAIT,
 1657                                     ("timewait"));
 1658                                 break;
 1659                         }
 1660                 }
 1661                 goto drop;
 1662         }
 1663 
 1664         /*
 1665          * RFC 1323 PAWS: If we have a timestamp reply on this segment
 1666          * and it's less than ts_recent, drop it.
 1667          */
 1668         if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
 1669             TSTMP_LT(to.to_tsval, tp->ts_recent)) {
 1670 
 1671                 /* Check to see if ts_recent is over 24 days old.  */
 1672                 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
 1673                         /*
 1674                          * Invalidate ts_recent.  If this segment updates
 1675                          * ts_recent, the age will be reset later and ts_recent
 1676                          * will get a valid value.  If it does not, setting
 1677                          * ts_recent to zero will at least satisfy the
 1678                          * requirement that zero be placed in the timestamp
 1679                          * echo reply when ts_recent isn't valid.  The
 1680                          * age isn't reset until we get a valid ts_recent
 1681                          * because we don't want out-of-order segments to be
 1682                          * dropped when ts_recent is old.
 1683                          */
 1684                         tp->ts_recent = 0;
 1685                 } else {
 1686                         tcpstat.tcps_rcvduppack++;
 1687                         tcpstat.tcps_rcvdupbyte += tlen;
 1688                         tcpstat.tcps_pawsdrop++;
 1689                         if (tlen)
 1690                                 goto dropafterack;
 1691                         goto drop;
 1692                 }
 1693         }
 1694 
 1695         /*
 1696          * T/TCP mechanism
 1697          *   If T/TCP was negotiated and the segment doesn't have CC,
 1698          *   or if its CC is wrong then drop the segment.
 1699          *   RST segments do not have to comply with this.
 1700          */
 1701         if ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) == (TF_REQ_CC|TF_RCVD_CC) &&
 1702             ((to.to_flags & TOF_CC) == 0 || tp->cc_recv != to.to_cc))
 1703                 goto dropafterack;
 1704 
 1705         /*
 1706          * In the SYN-RECEIVED state, validate that the packet belongs to
 1707          * this connection before trimming the data to fit the receive
 1708          * window.  Check the sequence number versus IRS since we know
 1709          * the sequence numbers haven't wrapped.  This is a partial fix
 1710          * for the "LAND" DoS attack.
 1711          */
 1712         if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
 1713                 rstreason = BANDLIM_RST_OPENPORT;
 1714                 goto dropwithreset;
 1715         }
 1716 
 1717         todrop = tp->rcv_nxt - th->th_seq;
 1718         if (todrop > 0) {
 1719                 if (thflags & TH_SYN) {
 1720                         thflags &= ~TH_SYN;
 1721                         th->th_seq++;
 1722                         if (th->th_urp > 1)
 1723                                 th->th_urp--;
 1724                         else
 1725                                 thflags &= ~TH_URG;
 1726                         todrop--;
 1727                 }
 1728                 /*
 1729                  * Following if statement from Stevens, vol. 2, p. 960.
 1730                  */
 1731                 if (todrop > tlen
 1732                     || (todrop == tlen && (thflags & TH_FIN) == 0)) {
 1733                         /*
 1734                          * Any valid FIN must be to the left of the window.
 1735                          * At this point the FIN must be a duplicate or out
 1736                          * of sequence; drop it.
 1737                          */
 1738                         thflags &= ~TH_FIN;
 1739 
 1740                         /*
 1741                          * Send an ACK to resynchronize and drop any data.
 1742                          * But keep on processing for RST or ACK.
 1743                          */
 1744                         tp->t_flags |= TF_ACKNOW;
 1745                         todrop = tlen;
 1746                         tcpstat.tcps_rcvduppack++;
 1747                         tcpstat.tcps_rcvdupbyte += todrop;
 1748                 } else {
 1749                         tcpstat.tcps_rcvpartduppack++;
 1750                         tcpstat.tcps_rcvpartdupbyte += todrop;
 1751                 }
 1752                 drop_hdrlen += todrop;  /* drop from the top afterwards */
 1753                 th->th_seq += todrop;
 1754                 tlen -= todrop;
 1755                 if (th->th_urp > todrop)
 1756                         th->th_urp -= todrop;
 1757                 else {
 1758                         thflags &= ~TH_URG;
 1759                         th->th_urp = 0;
 1760                 }
 1761         }
 1762 
 1763         /*
 1764          * If new data are received on a connection after the
 1765          * user processes are gone, then RST the other end.
 1766          */
 1767         if ((so->so_state & SS_NOFDREF) &&
 1768             tp->t_state > TCPS_CLOSE_WAIT && tlen) {
 1769                 tp = tcp_close(tp);
 1770                 tcpstat.tcps_rcvafterclose++;
 1771                 rstreason = BANDLIM_UNLIMITED;
 1772                 goto dropwithreset;
 1773         }
 1774 
 1775         /*
 1776          * If segment ends after window, drop trailing data
 1777          * (and PUSH and FIN); if nothing left, just ACK.
 1778          */
 1779         todrop = (th->th_seq+tlen) - (tp->rcv_nxt+tp->rcv_wnd);
 1780         if (todrop > 0) {
 1781                 tcpstat.tcps_rcvpackafterwin++;
 1782                 if (todrop >= tlen) {
 1783                         tcpstat.tcps_rcvbyteafterwin += tlen;
 1784                         /*
 1785                          * If a new connection request is received
 1786                          * while in TIME_WAIT, drop the old connection
 1787                          * and start over if the sequence numbers
 1788                          * are above the previous ones.
 1789                          */
 1790                         KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
 1791                         if (thflags & TH_SYN &&
 1792                             tp->t_state == TCPS_TIME_WAIT &&
 1793                             SEQ_GT(th->th_seq, tp->rcv_nxt)) {
 1794                                 tp = tcp_close(tp);
 1795                                 goto findpcb;
 1796                         }
 1797                         /*
 1798                          * If window is closed can only take segments at
 1799                          * window edge, and have to drop data and PUSH from
 1800                          * incoming segments.  Continue processing, but
 1801                          * remember to ack.  Otherwise, drop segment
 1802                          * and ack.
 1803                          */
 1804                         if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
 1805                                 tp->t_flags |= TF_ACKNOW;
 1806                                 tcpstat.tcps_rcvwinprobe++;
 1807                         } else
 1808                                 goto dropafterack;
 1809                 } else
 1810                         tcpstat.tcps_rcvbyteafterwin += todrop;
 1811                 m_adj(m, -todrop);
 1812                 tlen -= todrop;
 1813                 thflags &= ~(TH_PUSH|TH_FIN);
 1814         }
 1815 
 1816         /*
 1817          * If last ACK falls within this segment's sequence numbers,
 1818          * record its timestamp.
 1819          * NOTE: 
 1820          * 1) That the test incorporates suggestions from the latest
 1821          *    proposal of the tcplw@cray.com list (Braden 1993/04/26).
 1822          * 2) That updating only on newer timestamps interferes with
 1823          *    our earlier PAWS tests, so this check should be solely
 1824          *    predicated on the sequence space of this segment.
 1825          * 3) That we modify the segment boundary check to be 
 1826          *        Last.ACK.Sent <= SEG.SEQ + SEG.Len  
 1827          *    instead of RFC1323's
 1828          *        Last.ACK.Sent < SEG.SEQ + SEG.Len,
 1829          *    This modified check allows us to overcome RFC1323's
 1830          *    limitations as described in Stevens TCP/IP Illustrated
 1831          *    Vol. 2 p.869. In such cases, we can still calculate the
 1832          *    RTT correctly when RCV.NXT == Last.ACK.Sent.
 1833          */
 1834         if ((to.to_flags & TOF_TS) != 0 &&
 1835             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
 1836             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
 1837                 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
 1838                 tp->ts_recent_age = ticks;
 1839                 tp->ts_recent = to.to_tsval;
 1840         }
 1841 
 1842         /*
 1843          * If a SYN is in the window, then this is an
 1844          * error and we send an RST and drop the connection.
 1845          */
 1846         if (thflags & TH_SYN) {
 1847                 tp = tcp_drop(tp, ECONNRESET);
 1848                 rstreason = BANDLIM_UNLIMITED;
 1849                 goto drop;
 1850         }
 1851 
 1852         /*
 1853          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN
 1854          * flag is on (half-synchronized state), then queue data for
 1855          * later processing; else drop segment and return.
 1856          */
 1857         if ((thflags & TH_ACK) == 0) {
 1858                 if (tp->t_state == TCPS_SYN_RECEIVED ||
 1859                     (tp->t_flags & TF_NEEDSYN))
 1860                         goto step6;
 1861                 else
 1862                         goto drop;
 1863         }
 1864 
 1865         /*
 1866          * Ack processing.
 1867          */
 1868         switch (tp->t_state) {
 1869 
 1870         /*
 1871          * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
 1872          * ESTABLISHED state and continue processing.
 1873          * The ACK was checked above.
 1874          */
 1875         case TCPS_SYN_RECEIVED:
 1876 
 1877                 tcpstat.tcps_connects++;
 1878                 soisconnected(so);
 1879                 /* Do window scaling? */
 1880                 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
 1881                         (TF_RCVD_SCALE|TF_REQ_SCALE)) {
 1882                         tp->snd_scale = tp->requested_s_scale;
 1883                         tp->rcv_scale = tp->request_r_scale;
 1884                 }
 1885                 /*
 1886                  * Upon successful completion of 3-way handshake,
 1887                  * update cache.CC, pass any queued data to the user,
 1888                  * and advance state appropriately.
 1889                  */
 1890                 if (tcp_do_rfc1644) {
 1891                         tao.tao_cc = tp->cc_recv;
 1892                         tcp_hc_updatetao(&inp->inp_inc, TCP_HC_TAO_CC,
 1893                                          tp->cc_recv, 0);
 1894                 }
 1895                 /*
 1896                  * Make transitions:
 1897                  *      SYN-RECEIVED  -> ESTABLISHED
 1898                  *      SYN-RECEIVED* -> FIN-WAIT-1
 1899                  */
 1900                 tp->t_starttime = ticks;
 1901                 if (tp->t_flags & TF_NEEDFIN) {
 1902                         tp->t_state = TCPS_FIN_WAIT_1;
 1903                         tp->t_flags &= ~TF_NEEDFIN;
 1904                 } else {
 1905                         tp->t_state = TCPS_ESTABLISHED;
 1906                         callout_reset(tp->tt_keep, tcp_keepidle,
 1907                                       tcp_timer_keep, tp);
 1908                 }
 1909                 /*
 1910                  * If segment contains data or ACK, will call tcp_reass()
 1911                  * later; if not, do so now to pass queued data to user.
 1912                  */
 1913                 if (tlen == 0 && (thflags & TH_FIN) == 0)
 1914                         (void) tcp_reass(tp, (struct tcphdr *)0, 0,
 1915                             (struct mbuf *)0);
 1916                 tp->snd_wl1 = th->th_seq - 1;
 1917                 /* FALLTHROUGH */
 1918 
 1919         /*
 1920          * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
 1921          * ACKs.  If the ack is in the range
 1922          *      tp->snd_una < th->th_ack <= tp->snd_max
 1923          * then advance tp->snd_una to th->th_ack and drop
 1924          * data from the retransmission queue.  If this ACK reflects
 1925          * more up to date window information we update our window information.
 1926          */
 1927         case TCPS_ESTABLISHED:
 1928         case TCPS_FIN_WAIT_1:
 1929         case TCPS_FIN_WAIT_2:
 1930         case TCPS_CLOSE_WAIT:
 1931         case TCPS_CLOSING:
 1932         case TCPS_LAST_ACK:
 1933         case TCPS_TIME_WAIT:
 1934                 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
 1935                 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
 1936                         if (tlen == 0 && tiwin == tp->snd_wnd) {
 1937                                 tcpstat.tcps_rcvdupack++;
 1938                                 /*
 1939                                  * If we have outstanding data (other than
 1940                                  * a window probe), this is a completely
 1941                                  * duplicate ack (ie, window info didn't
 1942                                  * change), the ack is the biggest we've
 1943                                  * seen and we've seen exactly our rexmt
 1944                                  * threshhold of them, assume a packet
 1945                                  * has been dropped and retransmit it.
 1946                                  * Kludge snd_nxt & the congestion
 1947                                  * window so we send only this one
 1948                                  * packet.
 1949                                  *
 1950                                  * We know we're losing at the current
 1951                                  * window size so do congestion avoidance
 1952                                  * (set ssthresh to half the current window
 1953                                  * and pull our congestion window back to
 1954                                  * the new ssthresh).
 1955                                  *
 1956                                  * Dup acks mean that packets have left the
 1957                                  * network (they're now cached at the receiver)
 1958                                  * so bump cwnd by the amount in the receiver
 1959                                  * to keep a constant cwnd packets in the
 1960                                  * network.
 1961                                  */
 1962                                 if (!callout_active(tp->tt_rexmt) ||
 1963                                     th->th_ack != tp->snd_una)
 1964                                         tp->t_dupacks = 0;
 1965                                 else if (++tp->t_dupacks > tcprexmtthresh ||
 1966                                          ((tcp_do_newreno || tp->sack_enable) &&
 1967                                           IN_FASTRECOVERY(tp))) {
 1968                                         tp->snd_cwnd += tp->t_maxseg;
 1969                                         (void) tcp_output(tp);
 1970                                         goto drop;
 1971                                 } else if (tp->t_dupacks == tcprexmtthresh) {
 1972                                         tcp_seq onxt = tp->snd_nxt;
 1973                                         u_int win;
 1974 
 1975                                         /*
 1976                                          * If we're doing sack, check to
 1977                                          * see if we're already in sack
 1978                                          * recovery. If we're not doing sack,
 1979                                          * check to see if we're in newreno
 1980                                          * recovery.
 1981                                          */
 1982                                         if (tp->sack_enable) {
 1983                                                 if (IN_FASTRECOVERY(tp)) {
 1984                                                         tp->t_dupacks = 0;
 1985                                                         break;
 1986                                                 }
 1987                                         } else if (tcp_do_newreno) {
 1988                                                 if (SEQ_LEQ(th->th_ack,
 1989                                                     tp->snd_recover)) {
 1990                                                         tp->t_dupacks = 0;
 1991                                                         break;
 1992                                                 }
 1993                                         }
 1994                                         win = min(tp->snd_wnd, tp->snd_cwnd) /
 1995                                             2 / tp->t_maxseg;
 1996                                         if (win < 2)
 1997                                                 win = 2;
 1998                                         tp->snd_ssthresh = win * tp->t_maxseg;
 1999                                         ENTER_FASTRECOVERY(tp);
 2000                                         tp->snd_recover = tp->snd_max;
 2001                                         callout_stop(tp->tt_rexmt);
 2002                                         tp->t_rtttime = 0;
 2003                                         if (tp->sack_enable) {
 2004                                                 tcpstat.tcps_sack_recovery_episode++;
 2005                                                 tp->sack_newdata = tp->snd_nxt;
 2006                                                 tp->snd_cwnd = tp->t_maxseg;
 2007                                                 (void) tcp_output(tp);
 2008                                                 goto drop;
 2009                                         }
 2010                                         tp->snd_nxt = th->th_ack;
 2011                                         tp->snd_cwnd = tp->t_maxseg;
 2012                                         (void) tcp_output(tp);
 2013                                         KASSERT(tp->snd_limited <= 2,
 2014                                             ("tp->snd_limited too big"));
 2015                                         tp->snd_cwnd = tp->snd_ssthresh +
 2016                                              tp->t_maxseg *
 2017                                              (tp->t_dupacks - tp->snd_limited);
 2018                                         if (SEQ_GT(onxt, tp->snd_nxt))
 2019                                                 tp->snd_nxt = onxt;
 2020                                         goto drop;
 2021                                 } else if (tcp_do_rfc3042) {
 2022                                         u_long oldcwnd = tp->snd_cwnd;
 2023                                         tcp_seq oldsndmax = tp->snd_max;
 2024                                         u_int sent;
 2025 
 2026                                         KASSERT(tp->t_dupacks == 1 ||
 2027                                             tp->t_dupacks == 2,
 2028                                             ("dupacks not 1 or 2"));
 2029                                         if (tp->t_dupacks == 1)
 2030                                                 tp->snd_limited = 0;
 2031                                         tp->snd_cwnd =
 2032                                             (tp->snd_nxt - tp->snd_una) +
 2033                                             (tp->t_dupacks - tp->snd_limited) *
 2034                                             tp->t_maxseg;
 2035                                         (void) tcp_output(tp);
 2036                                         sent = tp->snd_max - oldsndmax;
 2037                                         if (sent > tp->t_maxseg) {
 2038                                                 KASSERT((tp->t_dupacks == 2 &&
 2039                                                     tp->snd_limited == 0) ||
 2040                                                    (sent == tp->t_maxseg + 1 &&
 2041                                                     tp->t_flags & TF_SENTFIN),
 2042                                                     ("sent too much"));
 2043                                                 tp->snd_limited = 2;
 2044                                         } else if (sent > 0)
 2045                                                 ++tp->snd_limited;
 2046                                         tp->snd_cwnd = oldcwnd;
 2047                                         goto drop;
 2048                                 }
 2049                         } else
 2050                                 tp->t_dupacks = 0;
 2051                         break;
 2052                 }
 2053 
 2054                 KASSERT(SEQ_GT(th->th_ack, tp->snd_una), ("th_ack <= snd_una"));
 2055 
 2056                 /*
 2057                  * If the congestion window was inflated to account
 2058                  * for the other side's cached packets, retract it.
 2059                  */
 2060                 if (tcp_do_newreno || tp->sack_enable) {
 2061                         if (IN_FASTRECOVERY(tp)) {
 2062                                 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
 2063                                         if (tp->sack_enable)
 2064                                                 tcp_sack_partialack(tp, th);
 2065                                         else
 2066                                                 tcp_newreno_partial_ack(tp, th);
 2067                                 } else {
 2068                                         /*
 2069                                          * Out of fast recovery.
 2070                                          * Window inflation should have left us
 2071                                          * with approximately snd_ssthresh
 2072                                          * outstanding data.
 2073                                          * But in case we would be inclined to
 2074                                          * send a burst, better to do it via
 2075                                          * the slow start mechanism.
 2076                                          */
 2077                                         if (SEQ_GT(th->th_ack +
 2078                                                         tp->snd_ssthresh,
 2079                                                    tp->snd_max))
 2080                                                 tp->snd_cwnd = tp->snd_max -
 2081                                                                 th->th_ack +
 2082                                                                 tp->t_maxseg;
 2083                                         else
 2084                                                 tp->snd_cwnd = tp->snd_ssthresh;
 2085                                 }
 2086                         }
 2087                 } else {
 2088                         if (tp->t_dupacks >= tcprexmtthresh &&
 2089                             tp->snd_cwnd > tp->snd_ssthresh)
 2090                                 tp->snd_cwnd = tp->snd_ssthresh;
 2091                 }
 2092                 tp->t_dupacks = 0;
 2093                 if (SEQ_GT(th->th_ack, tp->snd_max)) {
 2094                         tcpstat.tcps_rcvacktoomuch++;
 2095                         goto dropafterack;
 2096                 }
 2097                 /*
 2098                  * If we reach this point, ACK is not a duplicate,
 2099                  *     i.e., it ACKs something we sent.
 2100                  */
 2101                 if (tp->t_flags & TF_NEEDSYN) {
 2102                         /*
 2103                          * T/TCP: Connection was half-synchronized, and our
 2104                          * SYN has been ACK'd (so connection is now fully
 2105                          * synchronized).  Go to non-starred state,
 2106                          * increment snd_una for ACK of SYN, and check if
 2107                          * we can do window scaling.
 2108                          */
 2109                         tp->t_flags &= ~TF_NEEDSYN;
 2110                         tp->snd_una++;
 2111                         /* Do window scaling? */
 2112                         if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
 2113                                 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
 2114                                 tp->snd_scale = tp->requested_s_scale;
 2115                                 tp->rcv_scale = tp->request_r_scale;
 2116                         }
 2117                 }
 2118 
 2119 process_ACK:
 2120                 KASSERT(headlocked, ("tcp_input: process_ACK: head not "
 2121                     "locked"));
 2122                 INP_LOCK_ASSERT(inp);
 2123 
 2124                 acked = th->th_ack - tp->snd_una;
 2125                 tcpstat.tcps_rcvackpack++;
 2126                 tcpstat.tcps_rcvackbyte += acked;
 2127 
 2128                 /*
 2129                  * If we just performed our first retransmit, and the ACK
 2130                  * arrives within our recovery window, then it was a mistake
 2131                  * to do the retransmit in the first place.  Recover our
 2132                  * original cwnd and ssthresh, and proceed to transmit where
 2133                  * we left off.
 2134                  */
 2135                 if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
 2136                         ++tcpstat.tcps_sndrexmitbad;
 2137                         tp->snd_cwnd = tp->snd_cwnd_prev;
 2138                         tp->snd_ssthresh = tp->snd_ssthresh_prev;
 2139                         tp->snd_recover = tp->snd_recover_prev;
 2140                         if (tp->t_flags & TF_WASFRECOVERY)
 2141                                 ENTER_FASTRECOVERY(tp);
 2142                         tp->snd_nxt = tp->snd_max;
 2143                         tp->t_badrxtwin = 0;    /* XXX probably not required */
 2144                 }
 2145 
 2146                 /*
 2147                  * If we have a timestamp reply, update smoothed
 2148                  * round trip time.  If no timestamp is present but
 2149                  * transmit timer is running and timed sequence
 2150                  * number was acked, update smoothed round trip time.
 2151                  * Since we now have an rtt measurement, cancel the
 2152                  * timer backoff (cf., Phil Karn's retransmit alg.).
 2153                  * Recompute the initial retransmit timer.
 2154                  *
 2155                  * Some boxes send broken timestamp replies
 2156                  * during the SYN+ACK phase, ignore
 2157                  * timestamps of 0 or we could calculate a
 2158                  * huge RTT and blow up the retransmit timer.
 2159                  */
 2160                 if ((to.to_flags & TOF_TS) != 0 &&
 2161                     to.to_tsecr) {
 2162                         tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
 2163                 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
 2164                         tcp_xmit_timer(tp, ticks - tp->t_rtttime);
 2165                 }
 2166                 tcp_xmit_bandwidth_limit(tp, th->th_ack);
 2167 
 2168                 /*
 2169                  * If all outstanding data is acked, stop retransmit
 2170                  * timer and remember to restart (more output or persist).
 2171                  * If there is more data to be acked, restart retransmit
 2172                  * timer, using current (possibly backed-off) value.
 2173                  */
 2174                 if (th->th_ack == tp->snd_max) {
 2175                         callout_stop(tp->tt_rexmt);
 2176                         needoutput = 1;
 2177                 } else if (!callout_active(tp->tt_persist))
 2178                         callout_reset(tp->tt_rexmt, tp->t_rxtcur,
 2179                                       tcp_timer_rexmt, tp);
 2180 
 2181                 /*
 2182                  * If no data (only SYN) was ACK'd,
 2183                  *    skip rest of ACK processing.
 2184                  */
 2185                 if (acked == 0)
 2186                         goto step6;
 2187 
 2188                 /*
 2189                  * When new data is acked, open the congestion window.
 2190                  * If the window gives us less than ssthresh packets
 2191                  * in flight, open exponentially (maxseg per packet).
 2192                  * Otherwise open linearly: maxseg per window
 2193                  * (maxseg^2 / cwnd per packet).
 2194                  */
 2195                 if ((!tcp_do_newreno && !tp->sack_enable) ||
 2196                     !IN_FASTRECOVERY(tp)) {
 2197                         register u_int cw = tp->snd_cwnd;
 2198                         register u_int incr = tp->t_maxseg;
 2199                         if (cw > tp->snd_ssthresh)
 2200                                 incr = incr * incr / cw;
 2201                         tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
 2202                 }
 2203                 SOCKBUF_LOCK(&so->so_snd);
 2204                 if (acked > so->so_snd.sb_cc) {
 2205                         tp->snd_wnd -= so->so_snd.sb_cc;
 2206                         sbdrop_locked(&so->so_snd, (int)so->so_snd.sb_cc);
 2207                         ourfinisacked = 1;
 2208                 } else {
 2209                         sbdrop_locked(&so->so_snd, acked);
 2210                         tp->snd_wnd -= acked;
 2211                         ourfinisacked = 0;
 2212                 }
 2213                 sowwakeup_locked(so);
 2214                 /* detect una wraparound */
 2215                 if ((tcp_do_newreno || tp->sack_enable) &&
 2216                     !IN_FASTRECOVERY(tp) &&
 2217                     SEQ_GT(tp->snd_una, tp->snd_recover) &&
 2218                     SEQ_LEQ(th->th_ack, tp->snd_recover))
 2219                         tp->snd_recover = th->th_ack - 1;
 2220                 if ((tcp_do_newreno || tp->sack_enable) &&
 2221                     IN_FASTRECOVERY(tp) &&
 2222                     SEQ_GEQ(th->th_ack, tp->snd_recover))
 2223                         EXIT_FASTRECOVERY(tp);
 2224                 tp->snd_una = th->th_ack;
 2225                 if (tp->sack_enable) {
 2226                         if (SEQ_GT(tp->snd_una, tp->snd_recover))
 2227                                 tp->snd_recover = tp->snd_una;
 2228                 }
 2229                 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
 2230                         tp->snd_nxt = tp->snd_una;
 2231 
 2232                 switch (tp->t_state) {
 2233 
 2234                 /*
 2235                  * In FIN_WAIT_1 STATE in addition to the processing
 2236                  * for the ESTABLISHED state if our FIN is now acknowledged
 2237                  * then enter FIN_WAIT_2.
 2238                  */
 2239                 case TCPS_FIN_WAIT_1:
 2240                         if (ourfinisacked) {
 2241                                 /*
 2242                                  * If we can't receive any more
 2243                                  * data, then closing user can proceed.
 2244                                  * Starting the timer is contrary to the
 2245                                  * specification, but if we don't get a FIN
 2246                                  * we'll hang forever.
 2247                                  */
 2248                 /* XXXjl
 2249                  * we should release the tp also, and use a
 2250                  * compressed state.
 2251                  */
 2252                                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
 2253                                         soisdisconnected(so);
 2254                                         callout_reset(tp->tt_2msl, tcp_maxidle,
 2255                                                       tcp_timer_2msl, tp);
 2256                                 }
 2257                                 tp->t_state = TCPS_FIN_WAIT_2;
 2258                         }
 2259                         break;
 2260 
 2261                 /*
 2262                  * In CLOSING STATE in addition to the processing for
 2263                  * the ESTABLISHED state if the ACK acknowledges our FIN
 2264                  * then enter the TIME-WAIT state, otherwise ignore
 2265                  * the segment.
 2266                  */
 2267                 case TCPS_CLOSING:
 2268                         if (ourfinisacked) {
 2269                                 KASSERT(headlocked, ("tcp_input: process_ACK: "
 2270                                     "head not locked"));
 2271                                 tcp_twstart(tp);
 2272                                 INP_INFO_WUNLOCK(&tcbinfo);
 2273                                 m_freem(m);
 2274                                 return;
 2275                         }
 2276                         break;
 2277 
 2278                 /*
 2279                  * In LAST_ACK, we may still be waiting for data to drain
 2280                  * and/or to be acked, as well as for the ack of our FIN.
 2281                  * If our FIN is now acknowledged, delete the TCB,
 2282                  * enter the closed state and return.
 2283                  */
 2284                 case TCPS_LAST_ACK:
 2285                         if (ourfinisacked) {
 2286                                 tp = tcp_close(tp);
 2287                                 goto drop;
 2288                         }
 2289                         break;
 2290 
 2291                 /*
 2292                  * In TIME_WAIT state the only thing that should arrive
 2293                  * is a retransmission of the remote FIN.  Acknowledge
 2294                  * it and restart the finack timer.
 2295                  */
 2296                 case TCPS_TIME_WAIT:
 2297                         KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
 2298                         callout_reset(tp->tt_2msl, 2 * tcp_msl,
 2299                                       tcp_timer_2msl, tp);
 2300                         goto dropafterack;
 2301                 }
 2302         }
 2303 
 2304 step6:
 2305         KASSERT(headlocked, ("tcp_input: step6: head not locked"));
 2306         INP_LOCK_ASSERT(inp);
 2307 
 2308         /*
 2309          * Update window information.
 2310          * Don't look at window if no ACK: TAC's send garbage on first SYN.
 2311          */
 2312         if ((thflags & TH_ACK) &&
 2313             (SEQ_LT(tp->snd_wl1, th->th_seq) ||
 2314             (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
 2315              (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
 2316                 /* keep track of pure window updates */
 2317                 if (tlen == 0 &&
 2318                     tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
 2319                         tcpstat.tcps_rcvwinupd++;
 2320                 tp->snd_wnd = tiwin;
 2321                 tp->snd_wl1 = th->th_seq;
 2322                 tp->snd_wl2 = th->th_ack;
 2323                 if (tp->snd_wnd > tp->max_sndwnd)
 2324                         tp->max_sndwnd = tp->snd_wnd;
 2325                 needoutput = 1;
 2326         }
 2327 
 2328         /*
 2329          * Process segments with URG.
 2330          */
 2331         if ((thflags & TH_URG) && th->th_urp &&
 2332             TCPS_HAVERCVDFIN(tp->t_state) == 0) {
 2333                 /*
 2334                  * This is a kludge, but if we receive and accept
 2335                  * random urgent pointers, we'll crash in
 2336                  * soreceive.  It's hard to imagine someone
 2337                  * actually wanting to send this much urgent data.
 2338                  */
 2339                 SOCKBUF_LOCK(&so->so_rcv);
 2340                 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
 2341                         th->th_urp = 0;                 /* XXX */
 2342                         thflags &= ~TH_URG;             /* XXX */
 2343                         SOCKBUF_UNLOCK(&so->so_rcv);    /* XXX */
 2344                         goto dodata;                    /* XXX */
 2345                 }
 2346                 /*
 2347                  * If this segment advances the known urgent pointer,
 2348                  * then mark the data stream.  This should not happen
 2349                  * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
 2350                  * a FIN has been received from the remote side.
 2351                  * In these states we ignore the URG.
 2352                  *
 2353                  * According to RFC961 (Assigned Protocols),
 2354                  * the urgent pointer points to the last octet
 2355                  * of urgent data.  We continue, however,
 2356                  * to consider it to indicate the first octet
 2357                  * of data past the urgent section as the original
 2358                  * spec states (in one of two places).
 2359                  */
 2360                 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
 2361                         tp->rcv_up = th->th_seq + th->th_urp;
 2362                         so->so_oobmark = so->so_rcv.sb_cc +
 2363                             (tp->rcv_up - tp->rcv_nxt) - 1;
 2364                         if (so->so_oobmark == 0)
 2365                                 so->so_rcv.sb_state |= SBS_RCVATMARK;
 2366                         sohasoutofband(so);
 2367                         tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
 2368                 }
 2369                 SOCKBUF_UNLOCK(&so->so_rcv);
 2370                 /*
 2371                  * Remove out of band data so doesn't get presented to user.
 2372                  * This can happen independent of advancing the URG pointer,
 2373                  * but if two URG's are pending at once, some out-of-band
 2374                  * data may creep in... ick.
 2375                  */
 2376                 if (th->th_urp <= (u_long)tlen &&
 2377                     !(so->so_options & SO_OOBINLINE)) {
 2378                         /* hdr drop is delayed */
 2379                         tcp_pulloutofband(so, th, m, drop_hdrlen);
 2380                 }
 2381         } else {
 2382                 /*
 2383                  * If no out of band data is expected,
 2384                  * pull receive urgent pointer along
 2385                  * with the receive window.
 2386                  */
 2387                 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
 2388                         tp->rcv_up = tp->rcv_nxt;
 2389         }
 2390 dodata:                                                 /* XXX */
 2391         KASSERT(headlocked, ("tcp_input: dodata: head not locked"));
 2392         INP_LOCK_ASSERT(inp);
 2393 
 2394         /*
 2395          * Process the segment text, merging it into the TCP sequencing queue,
 2396          * and arranging for acknowledgment of receipt if necessary.
 2397          * This process logically involves adjusting tp->rcv_wnd as data
 2398          * is presented to the user (this happens in tcp_usrreq.c,
 2399          * case PRU_RCVD).  If a FIN has already been received on this
 2400          * connection then we just ignore the text.
 2401          */
 2402         if ((tlen || (thflags & TH_FIN)) &&
 2403             TCPS_HAVERCVDFIN(tp->t_state) == 0) {
 2404                 m_adj(m, drop_hdrlen);  /* delayed header drop */
 2405                 /*
 2406                  * Insert segment which includes th into TCP reassembly queue
 2407                  * with control block tp.  Set thflags to whether reassembly now
 2408                  * includes a segment with FIN.  This handles the common case
 2409                  * inline (segment is the next to be received on an established
 2410                  * connection, and the queue is empty), avoiding linkage into
 2411                  * and removal from the queue and repetition of various
 2412                  * conversions.
 2413                  * Set DELACK for segments received in order, but ack
 2414                  * immediately when segments are out of order (so
 2415                  * fast retransmit can work).
 2416                  */
 2417                 if (th->th_seq == tp->rcv_nxt &&
 2418                     LIST_EMPTY(&tp->t_segq) &&
 2419                     TCPS_HAVEESTABLISHED(tp->t_state)) {
 2420                         if (DELAY_ACK(tp))
 2421                                 tp->t_flags |= TF_DELACK;
 2422                         else
 2423                                 tp->t_flags |= TF_ACKNOW;
 2424                         tp->rcv_nxt += tlen;
 2425                         thflags = th->th_flags & TH_FIN;
 2426                         tcpstat.tcps_rcvpack++;
 2427                         tcpstat.tcps_rcvbyte += tlen;
 2428                         ND6_HINT(tp);
 2429                         SOCKBUF_LOCK(&so->so_rcv);
 2430                         if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
 2431                                 m_freem(m);
 2432                         else
 2433                                 sbappendstream_locked(&so->so_rcv, m);
 2434                         sorwakeup_locked(so);
 2435                 } else {
 2436                         thflags = tcp_reass(tp, th, &tlen, m);
 2437                         tp->t_flags |= TF_ACKNOW;
 2438                 }
 2439                 if (tp->sack_enable)
 2440                         tcp_update_sack_list(tp, th->th_seq, th->th_seq + tlen);
 2441                 /*
 2442                  * Note the amount of data that peer has sent into
 2443                  * our window, in order to estimate the sender's
 2444                  * buffer size.
 2445                  */
 2446                 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
 2447         } else {
 2448                 m_freem(m);
 2449                 thflags &= ~TH_FIN;
 2450         }
 2451 
 2452         /*
 2453          * If FIN is received ACK the FIN and let the user know
 2454          * that the connection is closing.
 2455          */
 2456         if (thflags & TH_FIN) {
 2457                 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
 2458                         socantrcvmore(so);
 2459                         /*
 2460                          * If connection is half-synchronized
 2461                          * (ie NEEDSYN flag on) then delay ACK,
 2462                          * so it may be piggybacked when SYN is sent.
 2463                          * Otherwise, since we received a FIN then no
 2464                          * more input can be expected, send ACK now.
 2465                          */
 2466                         if (tp->t_flags & TF_NEEDSYN)
 2467                                 tp->t_flags |= TF_DELACK;
 2468                         else
 2469                                 tp->t_flags |= TF_ACKNOW;
 2470                         tp->rcv_nxt++;
 2471                 }
 2472                 switch (tp->t_state) {
 2473 
 2474                 /*
 2475                  * In SYN_RECEIVED and ESTABLISHED STATES
 2476                  * enter the CLOSE_WAIT state.
 2477                  */
 2478                 case TCPS_SYN_RECEIVED:
 2479                         tp->t_starttime = ticks;
 2480                         /*FALLTHROUGH*/
 2481                 case TCPS_ESTABLISHED:
 2482                         tp->t_state = TCPS_CLOSE_WAIT;
 2483                         break;
 2484 
 2485                 /*
 2486                  * If still in FIN_WAIT_1 STATE FIN has not been acked so
 2487                  * enter the CLOSING state.
 2488                  */
 2489                 case TCPS_FIN_WAIT_1:
 2490                         tp->t_state = TCPS_CLOSING;
 2491                         break;
 2492 
 2493                 /*
 2494                  * In FIN_WAIT_2 state enter the TIME_WAIT state,
 2495                  * starting the time-wait timer, turning off the other
 2496                  * standard timers.
 2497                  */
 2498                 case TCPS_FIN_WAIT_2:
 2499                         KASSERT(headlocked == 1, ("tcp_input: dodata: "
 2500                             "TCP_FIN_WAIT_2: head not locked"));
 2501                         tcp_twstart(tp);
 2502                         INP_INFO_WUNLOCK(&tcbinfo);
 2503                         return;
 2504 
 2505                 /*
 2506                  * In TIME_WAIT state restart the 2 MSL time_wait timer.
 2507                  */
 2508                 case TCPS_TIME_WAIT:
 2509                         KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
 2510                         callout_reset(tp->tt_2msl, 2 * tcp_msl,
 2511                                       tcp_timer_2msl, tp);
 2512                         break;
 2513                 }
 2514         }
 2515         INP_INFO_WUNLOCK(&tcbinfo);
 2516         headlocked = 0;
 2517 #ifdef TCPDEBUG
 2518         if (so->so_options & SO_DEBUG)
 2519                 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
 2520                           &tcp_savetcp, 0);
 2521 #endif
 2522 
 2523         /*
 2524          * Return any desired output.
 2525          */
 2526         if (needoutput || (tp->t_flags & TF_ACKNOW))
 2527                 (void) tcp_output(tp);
 2528 
 2529 check_delack:
 2530         KASSERT(headlocked == 0, ("tcp_input: check_delack: head locked"));
 2531         INP_LOCK_ASSERT(inp);
 2532         if (tp->t_flags & TF_DELACK) {
 2533                 tp->t_flags &= ~TF_DELACK;
 2534                 callout_reset(tp->tt_delack, tcp_delacktime,
 2535                     tcp_timer_delack, tp);
 2536         }
 2537         INP_UNLOCK(inp);
 2538         return;
 2539 
 2540 dropafterack:
 2541         KASSERT(headlocked, ("tcp_input: dropafterack: head not locked"));
 2542         /*
 2543          * Generate an ACK dropping incoming segment if it occupies
 2544          * sequence space, where the ACK reflects our state.
 2545          *
 2546          * We can now skip the test for the RST flag since all
 2547          * paths to this code happen after packets containing
 2548          * RST have been dropped.
 2549          *
 2550          * In the SYN-RECEIVED state, don't send an ACK unless the
 2551          * segment we received passes the SYN-RECEIVED ACK test.
 2552          * If it fails send a RST.  This breaks the loop in the
 2553          * "LAND" DoS attack, and also prevents an ACK storm
 2554          * between two listening ports that have been sent forged
 2555          * SYN segments, each with the source address of the other.
 2556          */
 2557         if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
 2558             (SEQ_GT(tp->snd_una, th->th_ack) ||
 2559              SEQ_GT(th->th_ack, tp->snd_max)) ) {
 2560                 rstreason = BANDLIM_RST_OPENPORT;
 2561                 goto dropwithreset;
 2562         }
 2563 #ifdef TCPDEBUG
 2564         if (so->so_options & SO_DEBUG)
 2565                 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
 2566                           &tcp_savetcp, 0);
 2567 #endif
 2568         KASSERT(headlocked, ("headlocked should be 1"));
 2569         INP_INFO_WUNLOCK(&tcbinfo);
 2570         tp->t_flags |= TF_ACKNOW;
 2571         (void) tcp_output(tp);
 2572         INP_UNLOCK(inp);
 2573         m_freem(m);
 2574         return;
 2575 
 2576 dropwithreset:
 2577         KASSERT(headlocked, ("tcp_input: dropwithreset: head not locked"));
 2578         /*
 2579          * Generate a RST, dropping incoming segment.
 2580          * Make ACK acceptable to originator of segment.
 2581          * Don't bother to respond if destination was broadcast/multicast.
 2582          */
 2583         if ((thflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
 2584                 goto drop;
 2585         if (isipv6) {
 2586                 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
 2587                     IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
 2588                         goto drop;
 2589         } else {
 2590                 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
 2591                     IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
 2592                     ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
 2593                     in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
 2594                         goto drop;
 2595         }
 2596         /* IPv6 anycast check is done at tcp6_input() */
 2597 
 2598         /*
 2599          * Perform bandwidth limiting.
 2600          */
 2601         if (badport_bandlim(rstreason) < 0)
 2602                 goto drop;
 2603 
 2604 #ifdef TCPDEBUG
 2605         if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
 2606                 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
 2607                           &tcp_savetcp, 0);
 2608 #endif
 2609 
 2610         if (thflags & TH_ACK)
 2611                 /* mtod() below is safe as long as hdr dropping is delayed */
 2612                 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
 2613                             TH_RST);
 2614         else {
 2615                 if (thflags & TH_SYN)
 2616                         tlen++;
 2617                 /* mtod() below is safe as long as hdr dropping is delayed */
 2618                 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
 2619                             (tcp_seq)0, TH_RST|TH_ACK);
 2620         }
 2621 
 2622         if (tp)
 2623                 INP_UNLOCK(inp);
 2624         if (headlocked)
 2625                 INP_INFO_WUNLOCK(&tcbinfo);
 2626         return;
 2627 
 2628 drop:
 2629         /*
 2630          * Drop space held by incoming segment and return.
 2631          */
 2632 #ifdef TCPDEBUG
 2633         if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
 2634                 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
 2635                           &tcp_savetcp, 0);
 2636 #endif
 2637         if (tp)
 2638                 INP_UNLOCK(inp);
 2639         if (headlocked)
 2640                 INP_INFO_WUNLOCK(&tcbinfo);
 2641         m_freem(m);
 2642         return;
 2643 }
 2644 
 2645 /*
 2646  * Parse TCP options and place in tcpopt.
 2647  */
 2648 static void
 2649 tcp_dooptions(tp, to, cp, cnt, is_syn, th)
 2650         struct tcpcb *tp;
 2651         struct tcpopt *to;
 2652         u_char *cp;
 2653         int cnt;
 2654         int is_syn;
 2655         struct tcphdr *th;
 2656 {
 2657         int opt, optlen;
 2658 
 2659         to->to_flags = 0;
 2660         for (; cnt > 0; cnt -= optlen, cp += optlen) {
 2661                 opt = cp[0];
 2662                 if (opt == TCPOPT_EOL)
 2663                         break;
 2664                 if (opt == TCPOPT_NOP)
 2665                         optlen = 1;
 2666                 else {
 2667                         if (cnt < 2)
 2668                                 break;
 2669                         optlen = cp[1];
 2670                         if (optlen < 2 || optlen > cnt)
 2671                                 break;
 2672                 }
 2673                 switch (opt) {
 2674                 case TCPOPT_MAXSEG:
 2675                         if (optlen != TCPOLEN_MAXSEG)
 2676                                 continue;
 2677                         if (!is_syn)
 2678                                 continue;
 2679                         to->to_flags |= TOF_MSS;
 2680                         bcopy((char *)cp + 2,
 2681                             (char *)&to->to_mss, sizeof(to->to_mss));
 2682                         to->to_mss = ntohs(to->to_mss);
 2683                         break;
 2684                 case TCPOPT_WINDOW:
 2685                         if (optlen != TCPOLEN_WINDOW)
 2686                                 continue;
 2687                         if (! is_syn)
 2688                                 continue;
 2689                         to->to_flags |= TOF_SCALE;
 2690                         to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
 2691                         break;
 2692                 case TCPOPT_TIMESTAMP:
 2693                         if (optlen != TCPOLEN_TIMESTAMP)
 2694                                 continue;
 2695                         to->to_flags |= TOF_TS;
 2696                         bcopy((char *)cp + 2,
 2697                             (char *)&to->to_tsval, sizeof(to->to_tsval));
 2698                         to->to_tsval = ntohl(to->to_tsval);
 2699                         bcopy((char *)cp + 6,
 2700                             (char *)&to->to_tsecr, sizeof(to->to_tsecr));
 2701                         to->to_tsecr = ntohl(to->to_tsecr);
 2702                         /*
 2703                          * If echoed timestamp is later than the current time,
 2704                          * fall back to non RFC1323 RTT calculation.
 2705                          */
 2706                         if ((to->to_tsecr != 0) && TSTMP_GT(to->to_tsecr, ticks))
 2707                                 to->to_tsecr = 0;
 2708                         break;
 2709                 case TCPOPT_CC:
 2710                         if (optlen != TCPOLEN_CC)
 2711                                 continue;
 2712                         to->to_flags |= TOF_CC;
 2713                         bcopy((char *)cp + 2,
 2714                             (char *)&to->to_cc, sizeof(to->to_cc));
 2715                         to->to_cc = ntohl(to->to_cc);
 2716                         break;
 2717                 case TCPOPT_CCNEW:
 2718                         if (optlen != TCPOLEN_CC)
 2719                                 continue;
 2720                         if (!is_syn)
 2721                                 continue;
 2722                         to->to_flags |= TOF_CCNEW;
 2723                         bcopy((char *)cp + 2,
 2724                             (char *)&to->to_cc, sizeof(to->to_cc));
 2725                         to->to_cc = ntohl(to->to_cc);
 2726                         break;
 2727                 case TCPOPT_CCECHO:
 2728                         if (optlen != TCPOLEN_CC)
 2729                                 continue;
 2730                         if (!is_syn)
 2731                                 continue;
 2732                         to->to_flags |= TOF_CCECHO;
 2733                         bcopy((char *)cp + 2,
 2734                             (char *)&to->to_ccecho, sizeof(to->to_ccecho));
 2735                         to->to_ccecho = ntohl(to->to_ccecho);
 2736                         break;
 2737 #ifdef TCP_SIGNATURE
 2738                 /*
 2739                  * XXX In order to reply to a host which has set the
 2740                  * TCP_SIGNATURE option in its initial SYN, we have to
 2741                  * record the fact that the option was observed here
 2742                  * for the syncache code to perform the correct response.
 2743                  */
 2744                 case TCPOPT_SIGNATURE:
 2745                         if (optlen != TCPOLEN_SIGNATURE)
 2746                                 continue;
 2747                         to->to_flags |= (TOF_SIGNATURE | TOF_SIGLEN);
 2748                         break;
 2749 #endif
 2750                 case TCPOPT_SACK_PERMITTED:
 2751                         if (!tcp_do_sack ||
 2752                             optlen != TCPOLEN_SACK_PERMITTED)
 2753                                 continue;
 2754                         if (is_syn) {
 2755                                 /* MUST only be set on SYN */
 2756                                 to->to_flags |= TOF_SACK;
 2757                         }
 2758                         break;
 2759 
 2760                 case TCPOPT_SACK:
 2761                         if (!tp || tcp_sack_option(tp, th, cp, optlen))
 2762                                 continue;
 2763                         break;
 2764                 default:
 2765                         continue;
 2766                 }
 2767         }
 2768 }
 2769 
 2770 /*
 2771  * Pull out of band byte out of a segment so
 2772  * it doesn't appear in the user's data queue.
 2773  * It is still reflected in the segment length for
 2774  * sequencing purposes.
 2775  */
 2776 static void
 2777 tcp_pulloutofband(so, th, m, off)
 2778         struct socket *so;
 2779         struct tcphdr *th;
 2780         register struct mbuf *m;
 2781         int off;                /* delayed to be droped hdrlen */
 2782 {
 2783         int cnt = off + th->th_urp - 1;
 2784 
 2785         while (cnt >= 0) {
 2786                 if (m->m_len > cnt) {
 2787                         char *cp = mtod(m, caddr_t) + cnt;
 2788                         struct tcpcb *tp = sototcpcb(so);
 2789 
 2790                         tp->t_iobc = *cp;
 2791                         tp->t_oobflags |= TCPOOB_HAVEDATA;
 2792                         bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
 2793                         m->m_len--;
 2794                         if (m->m_flags & M_PKTHDR)
 2795                                 m->m_pkthdr.len--;
 2796                         return;
 2797                 }
 2798                 cnt -= m->m_len;
 2799                 m = m->m_next;
 2800                 if (m == 0)
 2801                         break;
 2802         }
 2803         panic("tcp_pulloutofband");
 2804 }
 2805 
 2806 /*
 2807  * Collect new round-trip time estimate
 2808  * and update averages and current timeout.
 2809  */
 2810 static void
 2811 tcp_xmit_timer(tp, rtt)
 2812         register struct tcpcb *tp;
 2813         int rtt;
 2814 {
 2815         register int delta;
 2816 
 2817         INP_LOCK_ASSERT(tp->t_inpcb);
 2818 
 2819         tcpstat.tcps_rttupdated++;
 2820         tp->t_rttupdated++;
 2821         if (tp->t_srtt != 0) {
 2822                 /*
 2823                  * srtt is stored as fixed point with 5 bits after the
 2824                  * binary point (i.e., scaled by 8).  The following magic
 2825                  * is equivalent to the smoothing algorithm in rfc793 with
 2826                  * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
 2827                  * point).  Adjust rtt to origin 0.
 2828                  */
 2829                 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
 2830                         - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
 2831 
 2832                 if ((tp->t_srtt += delta) <= 0)
 2833                         tp->t_srtt = 1;
 2834 
 2835                 /*
 2836                  * We accumulate a smoothed rtt variance (actually, a
 2837                  * smoothed mean difference), then set the retransmit
 2838                  * timer to smoothed rtt + 4 times the smoothed variance.
 2839                  * rttvar is stored as fixed point with 4 bits after the
 2840                  * binary point (scaled by 16).  The following is
 2841                  * equivalent to rfc793 smoothing with an alpha of .75
 2842                  * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
 2843                  * rfc793's wired-in beta.
 2844                  */
 2845                 if (delta < 0)
 2846                         delta = -delta;
 2847                 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
 2848                 if ((tp->t_rttvar += delta) <= 0)
 2849                         tp->t_rttvar = 1;
 2850                 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
 2851                     tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
 2852         } else {
 2853                 /*
 2854                  * No rtt measurement yet - use the unsmoothed rtt.
 2855                  * Set the variance to half the rtt (so our first
 2856                  * retransmit happens at 3*rtt).
 2857                  */
 2858                 tp->t_srtt = rtt << TCP_RTT_SHIFT;
 2859                 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
 2860                 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
 2861         }
 2862         tp->t_rtttime = 0;
 2863         tp->t_rxtshift = 0;
 2864 
 2865         /*
 2866          * the retransmit should happen at rtt + 4 * rttvar.
 2867          * Because of the way we do the smoothing, srtt and rttvar
 2868          * will each average +1/2 tick of bias.  When we compute
 2869          * the retransmit timer, we want 1/2 tick of rounding and
 2870          * 1 extra tick because of +-1/2 tick uncertainty in the
 2871          * firing of the timer.  The bias will give us exactly the
 2872          * 1.5 tick we need.  But, because the bias is
 2873          * statistical, we have to test that we don't drop below
 2874          * the minimum feasible timer (which is 2 ticks).
 2875          */
 2876         TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
 2877                       max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
 2878 
 2879         /*
 2880          * We received an ack for a packet that wasn't retransmitted;
 2881          * it is probably safe to discard any error indications we've
 2882          * received recently.  This isn't quite right, but close enough
 2883          * for now (a route might have failed after we sent a segment,
 2884          * and the return path might not be symmetrical).
 2885          */
 2886         tp->t_softerror = 0;
 2887 }
 2888 
 2889 /*
 2890  * Determine a reasonable value for maxseg size.
 2891  * If the route is known, check route for mtu.
 2892  * If none, use an mss that can be handled on the outgoing
 2893  * interface without forcing IP to fragment; if bigger than
 2894  * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
 2895  * to utilize large mbufs.  If no route is found, route has no mtu,
 2896  * or the destination isn't local, use a default, hopefully conservative
 2897  * size (usually 512 or the default IP max size, but no more than the mtu
 2898  * of the interface), as we can't discover anything about intervening
 2899  * gateways or networks.  We also initialize the congestion/slow start
 2900  * window to be a single segment if the destination isn't local.
 2901  * While looking at the routing entry, we also initialize other path-dependent
 2902  * parameters from pre-set or cached values in the routing entry.
 2903  *
 2904  * Also take into account the space needed for options that we
 2905  * send regularly.  Make maxseg shorter by that amount to assure
 2906  * that we can send maxseg amount of data even when the options
 2907  * are present.  Store the upper limit of the length of options plus
 2908  * data in maxopd.
 2909  *
 2910  *
 2911  * In case of T/TCP, we call this routine during implicit connection
 2912  * setup as well (offer = -1), to initialize maxseg from the cached
 2913  * MSS of our peer.
 2914  *
 2915  * NOTE that this routine is only called when we process an incoming
 2916  * segment. Outgoing SYN/ACK MSS settings are handled in tcp_mssopt().
 2917  */
 2918 void
 2919 tcp_mss(tp, offer)
 2920         struct tcpcb *tp;
 2921         int offer;
 2922 {
 2923         int rtt, mss;
 2924         u_long bufsize;
 2925         u_long maxmtu;
 2926         struct inpcb *inp = tp->t_inpcb;
 2927         struct socket *so;
 2928         struct hc_metrics_lite metrics;
 2929         struct rmxp_tao tao;
 2930         int origoffer = offer;
 2931 #ifdef INET6
 2932         int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
 2933         size_t min_protoh = isipv6 ?
 2934                             sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
 2935                             sizeof (struct tcpiphdr);
 2936 #else
 2937         const size_t min_protoh = sizeof(struct tcpiphdr);
 2938 #endif
 2939         bzero(&tao, sizeof(tao));
 2940 
 2941         /* initialize */
 2942 #ifdef INET6
 2943         if (isipv6) {
 2944                 maxmtu = tcp_maxmtu6(&inp->inp_inc);
 2945                 tp->t_maxopd = tp->t_maxseg = tcp_v6mssdflt;
 2946         } else
 2947 #endif
 2948         {
 2949                 maxmtu = tcp_maxmtu(&inp->inp_inc);
 2950                 tp->t_maxopd = tp->t_maxseg = tcp_mssdflt;
 2951         }
 2952         so = inp->inp_socket;
 2953 
 2954         /*
 2955          * no route to sender, stay with default mss and return
 2956          */
 2957         if (maxmtu == 0)
 2958                 return;
 2959 
 2960         /* what have we got? */
 2961         switch (offer) {
 2962                 case 0:
 2963                         /*
 2964                          * Offer == 0 means that there was no MSS on the SYN
 2965                          * segment, in this case we use tcp_mssdflt.
 2966                          */
 2967                         offer =
 2968 #ifdef INET6
 2969                                 isipv6 ? tcp_v6mssdflt :
 2970 #endif
 2971                                 tcp_mssdflt;
 2972                         break;
 2973 
 2974                 case -1:
 2975                         /*
 2976                          * Offer == -1 means that we didn't receive SYN yet,
 2977                          * use cached value in that case;
 2978                          */
 2979                         if (tcp_do_rfc1644)
 2980                                 tcp_hc_gettao(&inp->inp_inc, &tao);
 2981                         if (tao.tao_mssopt != 0)
 2982                                 offer = tao.tao_mssopt;
 2983                         /* FALLTHROUGH */
 2984 
 2985                 default:
 2986                         /*
 2987                          * Prevent DoS attack with too small MSS. Round up
 2988                          * to at least minmss.
 2989                          */
 2990                         offer = max(offer, tcp_minmss);
 2991                         /*
 2992                          * Sanity check: make sure that maxopd will be large
 2993                          * enough to allow some data on segments even if the
 2994                          * all the option space is used (40bytes).  Otherwise
 2995                          * funny things may happen in tcp_output.
 2996                          */
 2997                         offer = max(offer, 64);
 2998                         if (tcp_do_rfc1644)
 2999                                 tcp_hc_updatetao(&inp->inp_inc,
 3000                                                  TCP_HC_TAO_MSSOPT, 0, offer);
 3001         }
 3002 
 3003         /*
 3004          * rmx information is now retrieved from tcp_hostcache
 3005          */
 3006         tcp_hc_get(&inp->inp_inc, &metrics);
 3007 
 3008         /*
 3009          * if there's a discovered mtu int tcp hostcache, use it
 3010          * else, use the link mtu.
 3011          */
 3012         if (metrics.rmx_mtu)
 3013                 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
 3014         else {
 3015 #ifdef INET6
 3016                 if (isipv6) {
 3017                         mss = maxmtu - min_protoh;
 3018                         if (!path_mtu_discovery &&
 3019                             !in6_localaddr(&inp->in6p_faddr))
 3020                                 mss = min(mss, tcp_v6mssdflt);
 3021                 } else
 3022 #endif
 3023                 {
 3024                         mss = maxmtu - min_protoh;
 3025                         if (!path_mtu_discovery &&
 3026                             !in_localaddr(inp->inp_faddr))
 3027                                 mss = min(mss, tcp_mssdflt);
 3028                 }
 3029         }
 3030         mss = min(mss, offer);
 3031 
 3032         /*
 3033          * maxopd stores the maximum length of data AND options
 3034          * in a segment; maxseg is the amount of data in a normal
 3035          * segment.  We need to store this value (maxopd) apart
 3036          * from maxseg, because now every segment carries options
 3037          * and thus we normally have somewhat less data in segments.
 3038          */
 3039         tp->t_maxopd = mss;
 3040 
 3041         /*
 3042          * In case of T/TCP, origoffer==-1 indicates, that no segments
 3043          * were received yet.  In this case we just guess, otherwise
 3044          * we do the same as before T/TCP.
 3045          */
 3046         if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
 3047             (origoffer == -1 ||
 3048              (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
 3049                 mss -= TCPOLEN_TSTAMP_APPA;
 3050         if ((tp->t_flags & (TF_REQ_CC|TF_NOOPT)) == TF_REQ_CC &&
 3051             (origoffer == -1 ||
 3052              (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC))
 3053                 mss -= TCPOLEN_CC_APPA;
 3054         tp->t_maxseg = mss;
 3055 
 3056 #if     (MCLBYTES & (MCLBYTES - 1)) == 0
 3057                 if (mss > MCLBYTES)
 3058                         mss &= ~(MCLBYTES-1);
 3059 #else
 3060                 if (mss > MCLBYTES)
 3061                         mss = mss / MCLBYTES * MCLBYTES;
 3062 #endif
 3063         tp->t_maxseg = mss;
 3064 
 3065         /*
 3066          * If there's a pipesize, change the socket buffer to that size,
 3067          * don't change if sb_hiwat is different than default (then it
 3068          * has been changed on purpose with setsockopt).
 3069          * Make the socket buffers an integral number of mss units;
 3070          * if the mss is larger than the socket buffer, decrease the mss.
 3071          */
 3072         SOCKBUF_LOCK(&so->so_snd);
 3073         if ((so->so_snd.sb_hiwat == tcp_sendspace) && metrics.rmx_sendpipe)
 3074                 bufsize = metrics.rmx_sendpipe;
 3075         else
 3076                 bufsize = so->so_snd.sb_hiwat;
 3077         if (bufsize < mss)
 3078                 mss = bufsize;
 3079         else {
 3080                 bufsize = roundup(bufsize, mss);
 3081                 if (bufsize > sb_max)
 3082                         bufsize = sb_max;
 3083                 if (bufsize > so->so_snd.sb_hiwat)
 3084                         (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
 3085         }
 3086         SOCKBUF_UNLOCK(&so->so_snd);
 3087         tp->t_maxseg = mss;
 3088 
 3089         SOCKBUF_LOCK(&so->so_rcv);
 3090         if ((so->so_rcv.sb_hiwat == tcp_recvspace) && metrics.rmx_recvpipe)
 3091                 bufsize = metrics.rmx_recvpipe;
 3092         else
 3093                 bufsize = so->so_rcv.sb_hiwat;
 3094         if (bufsize > mss) {
 3095                 bufsize = roundup(bufsize, mss);
 3096                 if (bufsize > sb_max)
 3097                         bufsize = sb_max;
 3098                 if (bufsize > so->so_rcv.sb_hiwat)
 3099                         (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
 3100         }
 3101         SOCKBUF_UNLOCK(&so->so_rcv);
 3102         /*
 3103          * While we're here, check the others too
 3104          */
 3105         if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
 3106                 tp->t_srtt = rtt;
 3107                 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
 3108                 tcpstat.tcps_usedrtt++;
 3109                 if (metrics.rmx_rttvar) {
 3110                         tp->t_rttvar = metrics.rmx_rttvar;
 3111                         tcpstat.tcps_usedrttvar++;
 3112                 } else {
 3113                         /* default variation is +- 1 rtt */
 3114                         tp->t_rttvar =
 3115                             tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
 3116                 }
 3117                 TCPT_RANGESET(tp->t_rxtcur,
 3118                               ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
 3119                               tp->t_rttmin, TCPTV_REXMTMAX);
 3120         }
 3121         if (metrics.rmx_ssthresh) {
 3122                 /*
 3123                  * There's some sort of gateway or interface
 3124                  * buffer limit on the path.  Use this to set
 3125                  * the slow start threshhold, but set the
 3126                  * threshold to no less than 2*mss.
 3127                  */
 3128                 tp->snd_ssthresh = max(2 * mss, metrics.rmx_ssthresh);
 3129                 tcpstat.tcps_usedssthresh++;
 3130         }
 3131         if (metrics.rmx_bandwidth)
 3132                 tp->snd_bandwidth = metrics.rmx_bandwidth;
 3133 
 3134         /*
 3135          * Set the slow-start flight size depending on whether this
 3136          * is a local network or not.
 3137          *
 3138          * Extend this so we cache the cwnd too and retrieve it here.
 3139          * Make cwnd even bigger than RFC3390 suggests but only if we
 3140          * have previous experience with the remote host. Be careful
 3141          * not make cwnd bigger than remote receive window or our own
 3142          * send socket buffer. Maybe put some additional upper bound
 3143          * on the retrieved cwnd. Should do incremental updates to
 3144          * hostcache when cwnd collapses so next connection doesn't
 3145          * overloads the path again.
 3146          *
 3147          * RFC3390 says only do this if SYN or SYN/ACK didn't got lost.
 3148          * We currently check only in syncache_socket for that.
 3149          */
 3150 #define TCP_METRICS_CWND
 3151 #ifdef TCP_METRICS_CWND
 3152         if (metrics.rmx_cwnd)
 3153                 tp->snd_cwnd = max(mss,
 3154                                 min(metrics.rmx_cwnd / 2,
 3155                                  min(tp->snd_wnd, so->so_snd.sb_hiwat)));
 3156         else
 3157 #endif
 3158         if (tcp_do_rfc3390)
 3159                 tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
 3160 #ifdef INET6
 3161         else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
 3162                  (!isipv6 && in_localaddr(inp->inp_faddr)))
 3163 #else
 3164         else if (in_localaddr(inp->inp_faddr))
 3165 #endif
 3166                 tp->snd_cwnd = mss * ss_fltsz_local;
 3167         else
 3168                 tp->snd_cwnd = mss * ss_fltsz;
 3169 }
 3170 
 3171 /*
 3172  * Determine the MSS option to send on an outgoing SYN.
 3173  */
 3174 int
 3175 tcp_mssopt(inc)
 3176         struct in_conninfo *inc;
 3177 {
 3178         int mss = 0;
 3179         u_long maxmtu = 0;
 3180         u_long thcmtu = 0;
 3181         size_t min_protoh;
 3182 #ifdef INET6
 3183         int isipv6 = inc->inc_isipv6 ? 1 : 0;
 3184 #endif
 3185 
 3186         KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
 3187 
 3188 #ifdef INET6
 3189         if (isipv6) {
 3190                 mss = tcp_v6mssdflt;
 3191                 maxmtu = tcp_maxmtu6(inc);
 3192                 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
 3193                 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
 3194         } else
 3195 #endif
 3196         {
 3197                 mss = tcp_mssdflt;
 3198                 maxmtu = tcp_maxmtu(inc);
 3199                 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
 3200                 min_protoh = sizeof(struct tcpiphdr);
 3201         }
 3202         if (maxmtu && thcmtu)
 3203                 mss = min(maxmtu, thcmtu) - min_protoh;
 3204         else if (maxmtu || thcmtu)
 3205                 mss = max(maxmtu, thcmtu) - min_protoh;
 3206 
 3207         return (mss);
 3208 }
 3209 
 3210 
 3211 /*
 3212  * On a partial ack arrives, force the retransmission of the
 3213  * next unacknowledged segment.  Do not clear tp->t_dupacks.
 3214  * By setting snd_nxt to ti_ack, this forces retransmission timer to
 3215  * be started again.
 3216  */
 3217 static void
 3218 tcp_newreno_partial_ack(tp, th)
 3219         struct tcpcb *tp;
 3220         struct tcphdr *th;
 3221 {
 3222         tcp_seq onxt = tp->snd_nxt;
 3223         u_long  ocwnd = tp->snd_cwnd;
 3224 
 3225         callout_stop(tp->tt_rexmt);
 3226         tp->t_rtttime = 0;
 3227         tp->snd_nxt = th->th_ack;
 3228         /*
 3229          * Set snd_cwnd to one segment beyond acknowledged offset.
 3230          * (tp->snd_una has not yet been updated when this function is called.)
 3231          */
 3232         tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
 3233         tp->t_flags |= TF_ACKNOW;
 3234         (void) tcp_output(tp);
 3235         tp->snd_cwnd = ocwnd;
 3236         if (SEQ_GT(onxt, tp->snd_nxt))
 3237                 tp->snd_nxt = onxt;
 3238         /*
 3239          * Partial window deflation.  Relies on fact that tp->snd_una
 3240          * not updated yet.
 3241          */
 3242         tp->snd_cwnd -= (th->th_ack - tp->snd_una - tp->t_maxseg);
 3243 }
 3244 
 3245 /*
 3246  * Returns 1 if the TIME_WAIT state was killed and we should start over,
 3247  * looking for a pcb in the listen state.  Returns 0 otherwise.
 3248  */
 3249 static int
 3250 tcp_timewait(tw, to, th, m, tlen)
 3251         struct tcptw *tw;
 3252         struct tcpopt *to;
 3253         struct tcphdr *th;
 3254         struct mbuf *m;
 3255         int tlen;
 3256 {
 3257         int thflags;
 3258         tcp_seq seq;
 3259 #ifdef INET6
 3260         int isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
 3261 #else
 3262         const int isipv6 = 0;
 3263 #endif
 3264 
 3265         /* tcbinfo lock required for tcp_twclose(), tcp_2msl_reset. */
 3266         INP_INFO_WLOCK_ASSERT(&tcbinfo);
 3267         INP_LOCK_ASSERT(tw->tw_inpcb);
 3268 
 3269         thflags = th->th_flags;
 3270 
 3271         /*
 3272          * NOTE: for FIN_WAIT_2 (to be added later),
 3273          * must validate sequence number before accepting RST
 3274          */
 3275 
 3276         /*
 3277          * If the segment contains RST:
 3278          *      Drop the segment - see Stevens, vol. 2, p. 964 and
 3279          *      RFC 1337.
 3280          */
 3281         if (thflags & TH_RST)
 3282                 goto drop;
 3283 
 3284         /*
 3285          * If segment contains a SYN and CC [not CC.NEW] option:
 3286          *      if connection duration > MSL, drop packet and send RST;
 3287          *
 3288          *      if SEG.CC > CCrecv then is new SYN.
 3289          *          Complete close and delete TCPCB.  Then reprocess
 3290          *          segment, hoping to find new TCPCB in LISTEN state;
 3291          *
 3292          *      else must be old SYN; drop it.
 3293          * else do normal processing.
 3294          */
 3295         if ((thflags & TH_SYN) && (to->to_flags & TOF_CC) && tw->cc_recv != 0) {
 3296                 if ((ticks - tw->t_starttime) > tcp_msl)
 3297                         goto reset;
 3298                 if (CC_GT(to->to_cc, tw->cc_recv)) {
 3299                         (void) tcp_twclose(tw, 0);
 3300                         return (1);
 3301                 }
 3302                 goto drop;
 3303         }
 3304 
 3305 #if 0
 3306 /* PAWS not needed at the moment */
 3307         /*
 3308          * RFC 1323 PAWS: If we have a timestamp reply on this segment
 3309          * and it's less than ts_recent, drop it.
 3310          */
 3311         if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
 3312             TSTMP_LT(to.to_tsval, tp->ts_recent)) {
 3313                 if ((thflags & TH_ACK) == 0)
 3314                         goto drop;
 3315                 goto ack;
 3316         }
 3317         /*
 3318          * ts_recent is never updated because we never accept new segments.
 3319          */
 3320 #endif
 3321 
 3322         /*
 3323          * If a new connection request is received
 3324          * while in TIME_WAIT, drop the old connection
 3325          * and start over if the sequence numbers
 3326          * are above the previous ones.
 3327          */
 3328         if ((thflags & TH_SYN) && SEQ_GT(th->th_seq, tw->rcv_nxt)) {
 3329                 (void) tcp_twclose(tw, 0);
 3330                 return (1);
 3331         }
 3332 
 3333         /*
 3334          * Drop the the segment if it does not contain an ACK.
 3335          */
 3336         if ((thflags & TH_ACK) == 0)
 3337                 goto drop;
 3338 
 3339         /*
 3340          * Reset the 2MSL timer if this is a duplicate FIN.
 3341          */
 3342         if (thflags & TH_FIN) {
 3343                 seq = th->th_seq + tlen + (thflags & TH_SYN ? 1 : 0);
 3344                 if (seq + 1 == tw->rcv_nxt)
 3345                         tcp_timer_2msl_reset(tw, 2 * tcp_msl);
 3346         }
 3347 
 3348         /*
 3349          * Acknowledge the segment if it has data or is not a duplicate ACK.
 3350          */
 3351         if (thflags != TH_ACK || tlen != 0 ||
 3352             th->th_seq != tw->rcv_nxt || th->th_ack != tw->snd_nxt)
 3353                 tcp_twrespond(tw, TH_ACK);
 3354         goto drop;
 3355 
 3356 reset:
 3357         /*
 3358          * Generate a RST, dropping incoming segment.
 3359          * Make ACK acceptable to originator of segment.
 3360          * Don't bother to respond if destination was broadcast/multicast.
 3361          */
 3362         if (m->m_flags & (M_BCAST|M_MCAST))
 3363                 goto drop;
 3364         if (isipv6) {
 3365                 struct ip6_hdr *ip6;
 3366 
 3367                 /* IPv6 anycast check is done at tcp6_input() */
 3368                 ip6 = mtod(m, struct ip6_hdr *);
 3369                 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
 3370                     IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
 3371                         goto drop;
 3372         } else {
 3373                 struct ip *ip;
 3374 
 3375                 ip = mtod(m, struct ip *);
 3376                 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
 3377                     IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
 3378                     ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
 3379                     in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
 3380                         goto drop;
 3381         }
 3382         if (thflags & TH_ACK) {
 3383                 tcp_respond(NULL,
 3384                     mtod(m, void *), th, m, 0, th->th_ack, TH_RST);
 3385         } else {
 3386                 seq = th->th_seq + (thflags & TH_SYN ? 1 : 0);
 3387                 tcp_respond(NULL,
 3388                     mtod(m, void *), th, m, seq, 0, TH_RST|TH_ACK);
 3389         }
 3390         INP_UNLOCK(tw->tw_inpcb);
 3391         return (0);
 3392 
 3393 drop:
 3394         INP_UNLOCK(tw->tw_inpcb);
 3395         m_freem(m);
 3396         return (0);
 3397 }

Cache object: e5cde52d3f600a0a31d4936449e24f10


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.