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

Cache object: 25a8db9b5ceacc63ef0b77310111785b


[ 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.