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

Cache object: 238ee6ebf1d8d10f89ce15ed7fd357f4


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