home *** CD-ROM | disk | FTP | other *** search
/ High Voltage Shareware / high1.zip / high1 / DIR3 / KA9Q212.ZIP / TCPIN.C < prev    next >
C/C++ Source or Header  |  1993-07-16  |  25KB  |  906 lines

  1. /* Process incoming TCP segments. Page number references are to ARPA RFC-793,
  2.  * the TCP specification.
  3.  *
  4.  * Copyright 1991 Phil Karn, KA9Q
  5.  */
  6.  
  7. /****************************************************************************
  8. *    $Id: tcpin.c 1.2 93/07/16 11:51:15 ROOT_DOS Exp $
  9. *    09 May 93    1.2        GT    Fix warnings.                                    *
  10. *                            Throw away incoming packets when memory is low.    *
  11. ****************************************************************************/
  12.  
  13. #include "global.h"
  14. #include "timer.h"
  15. #include "mbuf.h"
  16. #include "netuser.h"
  17. #include "internet.h"
  18. #include "tcp.h"
  19. #include "icmp.h"
  20. #include "iface.h"
  21. #include "ip.h"
  22.  
  23. static void update __ARGS((struct tcb *tcb,struct tcp *seg,int16 length));
  24. static void proc_syn __ARGS((struct tcb *tcb,char tos,struct tcp *seg));
  25. static void add_reseq __ARGS((struct tcb *tcb,char tos,struct tcp *seg,
  26.     struct mbuf *bp,int16 length));
  27. static void get_reseq __ARGS((struct tcb *tcb,char *tos,struct tcp *seq,
  28.     struct mbuf **bp,int16 *length));
  29. static int trim __ARGS((struct tcb *tcb,struct tcp *seg,struct mbuf **bpp,
  30.     int16 *length));
  31. static int in_window __ARGS((struct tcb *tcb,int32 seq));
  32.  
  33. /* This function is called from IP with the IP header in machine byte order,
  34.  * along with a mbuf chain pointing to the TCP header.
  35.  */
  36. void
  37. tcp_input(iface,ip,bp,rxbroadcast)
  38. struct iface *iface;    /* Incoming interface (ignored) */
  39. struct mbuf *bp;    /* Data field, if any */
  40. struct ip *ip;        /* IP header */
  41. int rxbroadcast;    /* Incoming broadcast - discard if true */
  42. {
  43.     struct tcb *ntcb;
  44.     register struct tcb *tcb;    /* TCP Protocol control block */
  45.     struct tcp seg;            /* Local copy of segment header */
  46.     struct connection conn;        /* Local copy of addresses */
  47.     struct pseudo_header ph;    /* Pseudo-header for checksumming */
  48.     int hdrlen;            /* Length of TCP header */
  49.     int16 length;
  50.  
  51.     if(bp == NULLBUF)
  52.         return;
  53.  
  54.     tcpInSegs++;
  55.     if(rxbroadcast){
  56.         /* Any TCP packet arriving as a broadcast is
  57.          * to be completely IGNORED!!
  58.          */
  59.         free_p(bp);
  60.         return;
  61.     }
  62.  
  63.     if (availmem () < Memthresh)
  64.         {
  65.         /* Too little memory - throw away packet. */
  66.  
  67.         tcpInErrs++;
  68.         free_p (bp);
  69.         return;
  70.         }
  71.         
  72.     length = ip->length - IPLEN - ip->optlen;
  73.     ph.source = ip->source;
  74.     ph.dest = ip->dest;
  75.     ph.protocol = ip->protocol;
  76.     ph.length = length;
  77.     if(cksum(&ph,bp,length) != 0){
  78.         /* Checksum failed, ignore segment completely */
  79.         tcpInErrs++;
  80.         free_p(bp);
  81.         return;
  82.     }
  83.     /* Form local copy of TCP header in host byte order */
  84.     if((hdrlen = ntohtcp(&seg,&bp)) < 0){
  85.         /* TCP header is too small */
  86.         free_p(bp);
  87.         return;
  88.     }
  89.     length -= hdrlen;
  90.  
  91.     /* Fill in connection structure and find TCB */
  92.     conn.local.address = ip->dest;
  93.     conn.local.port = seg.dest;
  94.     conn.remote.address = ip->source;
  95.     conn.remote.port = seg.source;
  96.     
  97.     if((tcb = lookup_tcb(&conn)) == NULLTCB){
  98.         /* If this segment doesn't carry a SYN, reject it */
  99.         if(!seg.flags.syn){
  100.             free_p(bp);
  101.             reset(ip,&seg);
  102.             return;
  103.         }
  104.         /* See if there's a TCP_LISTEN on this socket with
  105.          * unspecified remote address and port
  106.          */
  107.         conn.remote.address = 0;
  108.         conn.remote.port = 0;
  109.         if((tcb = lookup_tcb(&conn)) == NULLTCB){
  110.             /* Nope, try unspecified local address too */
  111.             conn.local.address = 0;
  112.             if((tcb = lookup_tcb(&conn)) == NULLTCB){
  113.                 /* No LISTENs, so reject */
  114.                 free_p(bp);
  115.                 reset(ip,&seg);
  116.                 return;
  117.             }
  118.         }
  119.         /* We've found an server listen socket, so clone the TCB */
  120.         if(tcb->flags.clone){
  121.             ntcb = (struct tcb *)mallocw(sizeof (struct tcb));
  122.             ASSIGN(*ntcb,*tcb);
  123.             tcb = ntcb;
  124.             tcb->timer.arg = tcb;
  125.             /* Put on list */
  126.             tcb->next = Tcbs;
  127.             Tcbs = tcb;
  128.         }
  129.         /* Put all the socket info into the TCB */
  130.         tcb->conn.local.address = ip->dest;
  131.         tcb->conn.remote.address = ip->source;
  132.         tcb->conn.remote.port = seg.source;
  133.     }
  134.     tcb->flags.congest = ip->flags.congest;
  135.     /* Do unsynchronized-state processing (p. 65-68) */
  136.     switch(tcb->state){
  137.     case TCP_CLOSED:
  138.         free_p(bp);
  139.         reset(ip,&seg);
  140.         return;
  141.     case TCP_LISTEN:
  142.         if(seg.flags.rst){
  143.             free_p(bp);
  144.             return;
  145.         }
  146.         if(seg.flags.ack){
  147.             free_p(bp);
  148.             reset(ip,&seg);
  149.             return;
  150.         }
  151.         if(seg.flags.syn){
  152.             /* (Security check is bypassed) */
  153.             /* page 66 */
  154.             proc_syn(tcb,ip->tos,&seg);
  155.             send_syn(tcb);
  156.             setstate(tcb,TCP_SYN_RECEIVED);        
  157.             if(length != 0 || seg.flags.fin) {
  158.                 /* Continue processing if there's more */
  159.                 break;
  160.             }
  161.             tcp_output(tcb);
  162.         }
  163.         free_p(bp);    /* Unlikely to get here directly */
  164.         return;
  165.     case TCP_SYN_SENT:
  166.         if(seg.flags.ack){
  167.             if(!seq_within(seg.ack,tcb->iss+1,tcb->snd.nxt)){
  168.                 free_p(bp);
  169.                 reset(ip,&seg);
  170.                 return;
  171.             }
  172.         }
  173.         if(seg.flags.rst){    /* p 67 */
  174.             if(seg.flags.ack){
  175.                 /* The ack must be acceptable since we just checked it.
  176.                  * This is how the remote side refuses connect requests.
  177.                  */
  178.                 close_self(tcb,RESET);
  179.             }
  180.             free_p(bp);
  181.             return;
  182.         }
  183.         /* (Security check skipped here) */
  184.         /* Check incoming precedence; it must match if there's an ACK */
  185.         if(seg.flags.ack && PREC(ip->tos) != PREC(tcb->tos)){
  186.             free_p(bp);
  187.             reset(ip,&seg);
  188.             return;
  189.         }
  190.         if(seg.flags.syn){
  191.             proc_syn(tcb,ip->tos,&seg);
  192.             if(seg.flags.ack){
  193.                 /* Our SYN has been acked, otherwise the ACK
  194.                  * wouldn't have been valid.
  195.                  */
  196.                 update(tcb,&seg,length);
  197.                 setstate(tcb,TCP_ESTABLISHED);
  198.             } else {
  199.                 setstate(tcb,TCP_SYN_RECEIVED);
  200.             }
  201.             if(length != 0 || seg.flags.fin) {
  202.                 break;        /* Continue processing if there's more */
  203.             }
  204.             tcp_output(tcb);
  205.         } else {
  206.             free_p(bp);    /* Ignore if neither SYN or RST is set */
  207.         }
  208.         return;
  209.     }
  210.     /* We reach this point directly in any synchronized state. Note that
  211.      * if we fell through from LISTEN or SYN_SENT processing because of a
  212.      * data-bearing SYN, window trimming and sequence testing "cannot fail".
  213.      */
  214.  
  215.     /* Trim segment to fit receive window. */
  216.     if(trim(tcb,&seg,&bp,&length) == -1){
  217.         /* Segment is unacceptable */
  218.         if(!seg.flags.rst){    /* NEVER answer RSTs */
  219.             /* In SYN_RECEIVED state, answer a retransmitted SYN 
  220.              * with a retransmitted SYN/ACK.
  221.              */
  222.             if(tcb->state == TCP_SYN_RECEIVED)
  223.                 tcb->snd.ptr = tcb->snd.una;
  224.             tcb->flags.force = 1;
  225.             tcp_output(tcb);
  226.         }
  227.         return;
  228.     }
  229.     /* If segment isn't the next one expected, and there's data
  230.      * or flags associated with it, put it on the resequencing
  231.      * queue, ACK it and return.
  232.      *
  233.      * Processing the ACK in an out-of-sequence segment without
  234.      * flags or data should be safe, however.
  235.      */
  236.     if(seg.seq != tcb->rcv.nxt
  237.      && (length != 0 || seg.flags.syn || seg.flags.fin)){
  238.         add_reseq(tcb,ip->tos,&seg,bp,length);
  239.         tcb->flags.force = 1;
  240.         tcp_output(tcb);
  241.         return;
  242.     }
  243.     /* This loop first processes the current segment, and then
  244.      * repeats if it can process the resequencing queue.
  245.      */
  246.     for(;;){
  247.         /* We reach this point with an acceptable segment; all data and flags
  248.          * are in the window, and the starting sequence number equals rcv.nxt
  249.          * (p. 70)
  250.          */    
  251.         if(seg.flags.rst){
  252.             if(tcb->state == TCP_SYN_RECEIVED
  253.              && !tcb->flags.clone && !tcb->flags.active){
  254.                 /* Go back to listen state only if this was
  255.                  * not a cloned or active server TCB
  256.                  */
  257.                 setstate(tcb,TCP_LISTEN);
  258.             } else {
  259.                 close_self(tcb,RESET);
  260.             }
  261.             free_p(bp);
  262.             return;
  263.         }
  264.         /* (Security check skipped here) p. 71 */
  265.         /* Check for precedence mismatch or erroneous extra SYN */
  266.         if(PREC(ip->tos) != PREC(tcb->tos) || seg.flags.syn){
  267.             free_p(bp);
  268.             reset(ip,&seg);
  269.             return;
  270.         }
  271.         /* Check ack field p. 72 */
  272.         if(!seg.flags.ack){
  273.             free_p(bp);    /* All segments after synchronization must have ACK */
  274.             return;
  275.         }
  276.         /* Process ACK */
  277.         switch(tcb->state){
  278.         case TCP_SYN_RECEIVED:
  279.             if(seq_within(seg.ack,tcb->snd.una+1,tcb->snd.nxt)){
  280.                 update(tcb,&seg,length);
  281.                 setstate(tcb,TCP_ESTABLISHED);
  282.             } else {
  283.                 free_p(bp);
  284.                 reset(ip,&seg);
  285.                 return;
  286.             }
  287.             break;
  288.         case TCP_ESTABLISHED:
  289.         case TCP_CLOSE_WAIT:
  290.             update(tcb,&seg,length);
  291.             break;
  292.         case TCP_FINWAIT1:    /* p. 73 */
  293.             update(tcb,&seg,length);
  294.             if(tcb->sndcnt == 0){
  295.                 /* Our FIN is acknowledged */
  296.                 setstate(tcb,TCP_FINWAIT2);
  297.             }
  298.             break;
  299.         case TCP_FINWAIT2:
  300.             update(tcb,&seg,length);
  301.             break;
  302.         case TCP_CLOSING:
  303.             update(tcb,&seg,length);
  304.             if(tcb->sndcnt == 0){
  305.                 /* Our FIN is acknowledged */
  306.                 setstate(tcb,TCP_TIME_WAIT);
  307.                 set_timer(&tcb->timer,MSL2*1000L);
  308.                 start_timer(&tcb->timer);
  309.             }
  310.             break;
  311.         case TCP_LAST_ACK:
  312.             update(tcb,&seg,length);
  313.             if(tcb->sndcnt == 0){
  314.                 /* Our FIN is acknowledged, close connection */
  315.                 close_self(tcb,NORMAL);
  316.                 return;
  317.             }            
  318.             break;
  319.         case TCP_TIME_WAIT:
  320.             start_timer(&tcb->timer);
  321.             break;
  322.         }
  323.  
  324.         /* (URGent bit processing skipped here) */
  325.  
  326.         /* Process the segment text, if any, beginning at rcv.nxt (p. 74) */
  327.         if(length != 0){
  328.             switch(tcb->state){
  329.             case TCP_SYN_RECEIVED:
  330.             case TCP_ESTABLISHED:
  331.             case TCP_FINWAIT1:
  332.             case TCP_FINWAIT2:
  333.                 /* Place on receive queue */
  334.                 append(&tcb->rcvq,bp);
  335.                 tcb->rcvcnt += length;
  336.                 tcb->rcv.nxt += length;
  337.                 tcb->rcv.wnd -= length;
  338.                 tcb->flags.force = 1;
  339.                 /* Notify user */
  340.                 if(tcb->r_upcall)
  341.                     (*tcb->r_upcall)(tcb,tcb->rcvcnt);
  342.                 break;
  343.             default:
  344.                 /* Ignore segment text */
  345.                 free_p(bp);
  346.                 break;
  347.             }
  348.         }
  349.         /* process FIN bit (p 75) */
  350.         if(seg.flags.fin){
  351.             tcb->flags.force = 1;    /* Always respond with an ACK */
  352.  
  353.             switch(tcb->state){
  354.             case TCP_SYN_RECEIVED:
  355.             case TCP_ESTABLISHED:
  356.                 tcb->rcv.nxt++;
  357.                 setstate(tcb,TCP_CLOSE_WAIT);
  358.                 break;
  359.             case TCP_FINWAIT1:
  360.                 tcb->rcv.nxt++;
  361.                 if(tcb->sndcnt == 0){
  362.                     /* Our FIN has been acked; bypass TCP_CLOSING state */
  363.                     setstate(tcb,TCP_TIME_WAIT);
  364.                     set_timer(&tcb->timer,MSL2*1000L);
  365.                     start_timer(&tcb->timer);
  366.                 } else {
  367.                     setstate(tcb,TCP_CLOSING);
  368.                 }
  369.                 break;
  370.             case TCP_FINWAIT2:
  371.                 tcb->rcv.nxt++;
  372.                 setstate(tcb,TCP_TIME_WAIT);
  373.                 set_timer(&tcb->timer,MSL2*1000L);
  374.                 start_timer(&tcb->timer);
  375.                 break;
  376.             case TCP_CLOSE_WAIT:
  377.             case TCP_CLOSING:
  378.             case TCP_LAST_ACK:
  379.                 break;        /* Ignore */
  380.             case TCP_TIME_WAIT:    /* p 76 */
  381.                 start_timer(&tcb->timer);
  382.                 break;
  383.             }
  384.             /* Call the client again so he can see EOF */
  385.             if(tcb->r_upcall)
  386.                 (*tcb->r_upcall)(tcb,tcb->rcvcnt);
  387.         }
  388.         /* Scan the resequencing queue, looking for a segment we can handle,
  389.          * and freeing all those that are now obsolete.
  390.          */
  391.         while(tcb->reseq != NULLRESEQ && seq_ge(tcb->rcv.nxt,tcb->reseq->seg.seq)){
  392.             get_reseq(tcb,&ip->tos,&seg,&bp,&length);
  393.             if(trim(tcb,&seg,&bp,&length) == 0)
  394.                 goto gotone;
  395.             /* Segment is an old one; trim has freed it */
  396.         }
  397.         break;
  398. gotone:    ;
  399.     }
  400.     tcp_output(tcb);    /* Send any necessary ack */
  401. }
  402.  
  403. /* Process an incoming ICMP response */
  404. void
  405. tcp_icmp(icsource,source,dest,type,code,bpp)
  406. int32 icsource;            /* Sender of ICMP message (not used) */
  407. int32 source;            /* Original IP datagram source (i.e. us) */
  408. int32 dest;            /* Original IP datagram dest (i.e., them) */
  409. char type,code;            /* ICMP error codes */
  410. struct mbuf **bpp;        /* First 8 bytes of TCP header */
  411. {
  412.     struct tcp seg;
  413.     struct connection conn;
  414.     register struct tcb *tcb;
  415.  
  416.     /* Extract the socket info from the returned TCP header fragment
  417.      * Note that since this is a datagram we sent, the source fields
  418.      * refer to the local side.
  419.      */
  420.     ntohtcp(&seg,bpp);
  421.     conn.local.port = seg.source;
  422.     conn.remote.port = seg.dest;
  423.     conn.local.address = source;
  424.     conn.remote.address = dest;
  425.     if((tcb = lookup_tcb(&conn)) == NULLTCB)
  426.         return;    /* Unknown connection, ignore */
  427.  
  428.     /* Verify that the sequence number in the returned segment corresponds
  429.      * to something currently unacknowledged. If not, it can safely
  430.      * be ignored.
  431.      */
  432.     if(!seq_within(seg.seq,tcb->snd.una,tcb->snd.nxt))
  433.         return;
  434.  
  435.     /* Destination Unreachable and Time Exceeded messages never kill a
  436.      * connection; the info is merely saved for future reference.
  437.      */
  438.     switch(uchar(type)){
  439.     case ICMP_DEST_UNREACH:
  440.     case ICMP_TIME_EXCEED:
  441.         tcb->type = type;
  442.         tcb->code = code;
  443.         break;
  444.     case ICMP_QUENCH:
  445.         /* Source quench; cut the congestion window in half,
  446.          * but don't let it go below one packet
  447.          */
  448.         tcb->cwind /= 2;
  449.         tcb->cwind = max(tcb->mss,tcb->cwind);
  450.         break;
  451.     }
  452. }
  453. /* Send an acceptable reset (RST) response for this segment
  454.  * The RST reply is composed in place on the input segment
  455.  */
  456. void
  457. reset(ip,seg)
  458. struct ip *ip;            /* Offending IP header */
  459. register struct tcp *seg;    /* Offending TCP header */
  460. {
  461.     struct mbuf *hbp;
  462.     struct pseudo_header ph;
  463.     int16 tmp;
  464.  
  465.     if(seg->flags.rst)
  466.         return;    /* Never send an RST in response to an RST */
  467.  
  468.     /* Compose the RST IP pseudo-header, swapping addresses */
  469.     ph.source = ip->dest;
  470.     ph.dest = ip->source;
  471.     ph.protocol = TCP_PTCL;
  472.     ph.length = TCPLEN;
  473.  
  474.     /* Swap port numbers */
  475.     tmp = seg->source;
  476.     seg->source = seg->dest;
  477.     seg->dest = tmp;
  478.  
  479.     if(seg->flags.ack){
  480.         /* This reset is being sent to clear a half-open connection.
  481.          * Set the sequence number of the RST to the incoming ACK
  482.          * so it will be acceptable.
  483.          */
  484.         seg->flags.ack = 0;
  485.         seg->seq = seg->ack;
  486.         seg->ack = 0;
  487.     } else {
  488.         /* We're rejecting a connect request (SYN) from TCP_LISTEN state
  489.          * so we have to "acknowledge" their SYN.
  490.          */
  491.         seg->flags.ack = 1;
  492.         seg->ack = seg->seq;
  493.         seg->seq = 0;
  494.         if(seg->flags.syn)
  495.             seg->ack++;
  496.     }
  497.     /* Set remaining parts of packet */
  498.     seg->flags.urg = 0;
  499.     seg->flags.psh = 0;
  500.     seg->flags.rst = 1;
  501.     seg->flags.syn = 0;
  502.     seg->flags.fin = 0;
  503.     seg->wnd = 0;
  504.     seg->up = 0;
  505.     seg->mss = 0;
  506.     seg->optlen = 0;
  507.     if((hbp = htontcp(seg,NULLBUF,&ph)) == NULLBUF)
  508.         return;
  509.     /* Ship it out (note swap of addresses) */
  510.     ip_send(ip->dest,ip->source,TCP_PTCL,ip->tos,0,hbp,ph.length,0,0);
  511.     tcpOutRsts++;
  512. }
  513.  
  514. /* Process an incoming acknowledgement and window indication.
  515.  * From page 72.
  516.  */
  517. static void
  518. update(tcb,seg,length)
  519. register struct tcb *tcb;
  520. register struct tcp *seg;
  521. int16 length;
  522. {
  523.     int16 acked;
  524.     int16 expand;
  525.  
  526.     acked = 0;
  527.     if(seq_gt(seg->ack,tcb->snd.nxt)){
  528.         tcb->flags.force = 1;    /* Acks something not yet sent */
  529.         return;
  530.     }
  531.     /* Decide if we need to do a window update.
  532.      * This is always checked whenever a legal ACK is received,
  533.      * even if it doesn't actually acknowledge anything,
  534.      * because it might be a spontaneous window reopening.
  535.      */
  536.     if(seq_gt(seg->seq,tcb->snd.wl1) || ((seg->seq == tcb->snd.wl1) 
  537.      && seq_ge(seg->ack,tcb->snd.wl2))){
  538.         /* If the window had been closed, crank back the
  539.          * send pointer so we'll immediately resume transmission.
  540.          * Otherwise we'd have to wait until the next probe.
  541.          */
  542.         if(tcb->snd.wnd == 0 && seg->wnd != 0)
  543.             tcb->snd.ptr = tcb->snd.una;
  544.         tcb->snd.wnd = seg->wnd;
  545.         tcb->snd.wl1 = seg->seq;
  546.         tcb->snd.wl2 = seg->ack;
  547.     }
  548.     /* See if anything new is being acknowledged */
  549.     if(!seq_gt(seg->ack,tcb->snd.una)){
  550.         if(seg->ack != tcb->snd.una)
  551.             return;    /* Old ack, ignore */
  552.  
  553.         if(length != 0 || seg->flags.syn || seg->flags.fin)
  554.             return;    /* Nothing acked, but there is data */
  555.  
  556.         /* Van Jacobson "fast recovery" code */
  557.         if(++tcb->dupacks == TCPDUPACKS){
  558.             /* We've had a burst of do-nothing acks, so
  559.              * we almost certainly lost a packet.
  560.              * Resend it now to avoid a timeout. (This is
  561.              * Van Jacobson's 'quick recovery' algorithm.)
  562.              */
  563.             int32 ptrsave;
  564.  
  565.             /* Knock the threshold down just as though
  566.              * this were a timeout, since we've had
  567.              * network congestion.
  568.              */
  569.             tcb->ssthresh = tcb->cwind/2;
  570.             tcb->ssthresh = max(tcb->ssthresh,tcb->mss);
  571.  
  572.             /* Manipulate the machinery in tcp_output() to
  573.              * retransmit just the missing packet
  574.              */
  575.             ptrsave = tcb->snd.ptr;
  576.             tcb->snd.ptr = tcb->snd.una;
  577.             tcb->cwind = tcb->mss;
  578.             tcp_output(tcb);
  579.             tcb->snd.ptr = ptrsave;
  580.  
  581.             /* "Inflate" the congestion window, pretending as
  582.              * though the duplicate acks were normally acking
  583.              * the packets beyond the one that was lost.
  584.              */
  585.             tcb->cwind = tcb->ssthresh + TCPDUPACKS*tcb->mss;
  586.         } else if(tcb->dupacks > TCPDUPACKS){
  587.             /* Continue to inflate the congestion window
  588.              * until the acks finally get "unstuck".
  589.              */
  590.             tcb->cwind += tcb->mss;
  591.         }
  592.         return;
  593.     }
  594.     if(tcb->dupacks >= TCPDUPACKS && tcb->cwind > tcb->ssthresh){
  595.         /* The acks have finally gotten "unstuck". So now we
  596.          * can "deflate" the congestion window, i.e. take it
  597.          * back down to where it would be after slow start
  598.          * finishes.
  599.          */
  600.         tcb->cwind = tcb->ssthresh;
  601.     }
  602.     tcb->dupacks = 0;
  603.  
  604.     /* We're here, so the ACK must have actually acked something */
  605.     acked = seg->ack - tcb->snd.una;
  606.  
  607.     /* Expand congestion window if not already at limit and if
  608.      * this packet wasn't retransmitted
  609.      */
  610.     if(tcb->cwind < tcb->snd.wnd && !tcb->flags.retran){
  611.         if(tcb->cwind < tcb->ssthresh){
  612.             /* Still doing slow start/CUTE, expand by amount acked */
  613.             expand = min(acked,tcb->mss);
  614.         } else {
  615.             /* Steady-state test of extra path capacity */
  616.             expand = ((long)tcb->mss * tcb->mss) / tcb->cwind;
  617.         }
  618.         /* Guard against arithmetic overflow */
  619.         if(tcb->cwind + expand < tcb->cwind)
  620.             expand = (int16) (MAXINT16 - tcb->cwind);
  621.  
  622.         /* Don't expand beyond the offered window */
  623.         if(tcb->cwind + expand > tcb->snd.wnd)
  624.             expand = tcb->snd.wnd - tcb->cwind;
  625.  
  626.         if(expand != 0){
  627. #ifdef    notdef
  628.             /* Kick up the mean deviation estimate to prevent
  629.              * unnecessary retransmission should we already be
  630.              * bandwidth limited
  631.              */
  632.             tcb->mdev += ((long)tcb->srtt * expand) / tcb->cwind;
  633. #endif
  634.             tcb->cwind += expand;
  635.         }
  636.     }
  637.     /* Round trip time estimation */
  638.     if(tcb->flags.rtt_run && seq_ge(seg->ack,tcb->rttseq)){
  639.         /* A timed sequence number has been acked */
  640.         tcb->flags.rtt_run = 0;
  641.         if(!(tcb->flags.retran)){
  642.             int32 rtt;    /* measured round trip time */
  643.             int32 abserr;    /* abs(rtt - srtt) */
  644.  
  645.             /* This packet was sent only once and now
  646.              * it's been acked, so process the round trip time
  647.              */
  648.             rtt = msclock() - tcb->rtt_time;
  649.  
  650.             abserr = (rtt > tcb->srtt) ? rtt - tcb->srtt : tcb->srtt - rtt;
  651.             /* Run SRTT and MDEV integrators, with rounding */
  652.             tcb->srtt = ((AGAIN-1)*tcb->srtt + rtt + (AGAIN/2)) >> LAGAIN;
  653.             tcb->mdev = ((DGAIN-1)*tcb->mdev + abserr + (DGAIN/2)) >> LDGAIN;
  654.  
  655.             rtt_add(tcb->conn.remote.address,rtt);
  656.             /* Reset the backoff level */
  657.             tcb->backoff = 0;
  658.         }
  659.     }
  660.     tcb->sndcnt -= acked;    /* Update virtual byte count on snd queue */
  661.     tcb->snd.una = seg->ack;
  662.  
  663.     /* If we're waiting for an ack of our SYN, note it and adjust count */
  664.     if(!(tcb->flags.synack)){
  665.         tcb->flags.synack = 1;
  666.         acked--;    /* One less byte to pull from real snd queue */
  667.     }
  668.     /* Remove acknowledged bytes from the send queue and update the
  669.      * unacknowledged pointer. If a FIN is being acked,
  670.      * pullup won't be able to remove it from the queue, but that
  671.      * causes no harm.
  672.      */
  673.     pullup(&tcb->sndq,NULLCHAR,acked);
  674.  
  675.     /* Stop retransmission timer, but restart it if there is still
  676.      * unacknowledged data. If there is no more unacked data,
  677.      * the transmitter has gone at least momentarily idle, so
  678.      * record the time for the VJ restart-slowstart rule.
  679.      */    
  680.     stop_timer(&tcb->timer);
  681.     if(tcb->snd.una != tcb->snd.nxt)
  682.         start_timer(&tcb->timer);
  683.     else
  684.         tcb->lastactive = msclock();
  685.  
  686.     /* If retransmissions have been occurring, make sure the
  687.      * send pointer doesn't repeat ancient history
  688.      */
  689.     if(seq_lt(tcb->snd.ptr,tcb->snd.una))
  690.         tcb->snd.ptr = tcb->snd.una;
  691.  
  692.     /* Clear the retransmission flag since the oldest
  693.      * unacknowledged segment (the only one that is ever retransmitted)
  694.      * has now been acked.
  695.      */
  696.     tcb->flags.retran = 0;
  697.  
  698.     /* If outgoing data was acked, notify the user so he can send more
  699.      * unless we've already sent a FIN.
  700.      */
  701.     if(acked != 0 && tcb->t_upcall
  702.      && (tcb->state == TCP_ESTABLISHED || tcb->state == TCP_CLOSE_WAIT)){
  703.         (*tcb->t_upcall)(tcb,tcb->window - tcb->sndcnt);
  704.     }
  705. }
  706.  
  707. /* Determine if the given sequence number is in our receiver window.
  708.  * NB: must not be used when window is closed!
  709.  */
  710. static
  711. int
  712. in_window(tcb,seq)
  713. struct tcb *tcb;
  714. int32 seq;
  715. {
  716.     return seq_within(seq,tcb->rcv.nxt,(int32)(tcb->rcv.nxt+tcb->rcv.wnd-1));
  717. }
  718.  
  719. /* Process an incoming SYN */
  720. static void
  721. proc_syn(tcb,tos,seg)
  722. register struct tcb *tcb;
  723. char tos;
  724. struct tcp *seg;
  725. {
  726.     int16 mtu;
  727.     struct tcp_rtt *tp;
  728.  
  729.     tcb->flags.force = 1;    /* Always send a response */
  730.  
  731.     /* Note: It's not specified in RFC 793, but SND.WL1 and
  732.      * SND.WND are initialized here since it's possible for the
  733.      * window update routine in update() to fail depending on the
  734.      * IRS if they are left unitialized.
  735.      */
  736.     /* Check incoming precedence and increase if higher */
  737.     if(PREC(tos) > PREC(tcb->tos))
  738.         tcb->tos = tos;
  739.     tcb->rcv.nxt = seg->seq + 1;    /* p 68 */
  740.     tcb->snd.wl1 = tcb->irs = seg->seq;
  741.     tcb->snd.wnd = seg->wnd;
  742.     if(seg->mss != 0)
  743.         tcb->mss = seg->mss;
  744.     /* Check the MTU of the interface we'll use to reach this guy
  745.      * and lower the MSS so that unnecessary fragmentation won't occur
  746.      */
  747.     if((mtu = ip_mtu(tcb->conn.remote.address)) != 0){
  748.         /* Allow space for the TCP and IP headers */
  749.         mtu -= TCPLEN + IPLEN;
  750.         tcb->cwind = tcb->mss = min(mtu,tcb->mss);
  751.     }
  752.     /* See if there's round-trip time experience */
  753.     if((tp = rtt_get(tcb->conn.remote.address)) != NULLRTT){
  754.         tcb->srtt = tp->srtt;
  755.         tcb->mdev = tp->mdev;
  756.     }
  757. }
  758.  
  759. /* Generate an initial sequence number and put a SYN on the send queue */
  760. void
  761. send_syn(tcb)
  762. register struct tcb *tcb;
  763. {
  764.     tcb->iss = geniss();
  765.     tcb->rttseq = tcb->snd.wl2 = tcb->snd.una = tcb->iss;
  766.     tcb->snd.ptr = tcb->snd.nxt = tcb->rttseq;
  767.     tcb->sndcnt++;
  768.     tcb->flags.force = 1;
  769. }
  770.  
  771. /* Add an entry to the resequencing queue in the proper place */
  772. static void
  773. add_reseq(tcb,tos,seg,bp,length)
  774. struct tcb *tcb;
  775. char tos;
  776. struct tcp *seg;
  777. struct mbuf *bp;
  778. int16 length;
  779. {
  780.     register struct reseq *rp,*rp1;
  781.  
  782.     /* Allocate reassembly descriptor */
  783.     if((rp = (struct reseq *)malloc(sizeof (struct reseq))) == NULLRESEQ){
  784.         /* No space, toss on floor */
  785.         free_p(bp);
  786.         return;
  787.     }
  788.     ASSIGN(rp->seg,*seg);
  789.     rp->tos = tos;
  790.     rp->bp = bp;
  791.     rp->length = length;
  792.  
  793.     /* Place on reassembly list sorting by starting seq number */
  794.     rp1 = tcb->reseq;
  795.     if(rp1 == NULLRESEQ || seq_lt(seg->seq,rp1->seg.seq)){
  796.         /* Either the list is empty, or we're less than all other
  797.          * entries; insert at beginning.
  798.          */
  799.         rp->next = rp1;
  800.         tcb->reseq = rp;
  801.     } else {
  802.         /* Find the last entry less than us */
  803.         for(;;){
  804.             if(rp1->next == NULLRESEQ || seq_lt(seg->seq,rp1->next->seg.seq)){
  805.                 /* We belong just after this one */
  806.                 rp->next = rp1->next;
  807.                 rp1->next = rp;
  808.                 break;
  809.             }
  810.             rp1 = rp1->next;
  811.         }
  812.     }
  813. }
  814.  
  815. /* Fetch the first entry off the resequencing queue */
  816. static void
  817. get_reseq(tcb,tos,seg,bp,length)
  818. register struct tcb *tcb;
  819. char *tos;
  820. struct tcp *seg;
  821. struct mbuf **bp;
  822. int16 *length;
  823. {
  824.     register struct reseq *rp;
  825.  
  826.     if((rp = tcb->reseq) == NULLRESEQ)
  827.         return;
  828.  
  829.     tcb->reseq = rp->next;
  830.  
  831.     *tos = rp->tos;
  832.     ASSIGN(*seg,rp->seg);
  833.     *bp = rp->bp;
  834.     *length = rp->length;
  835.     free((char *)rp);
  836. }
  837.  
  838. /* Trim segment to fit window. Return 0 if OK, -1 if segment is
  839.  * unacceptable.
  840.  */
  841. static int
  842. trim(tcb,seg,bpp,length)
  843. register struct tcb *tcb;
  844. register struct tcp *seg;
  845. struct mbuf **bpp;
  846. int16 *length;
  847. {
  848.     long dupcnt,excess;
  849.     int16 len;        /* Segment length including flags */
  850.     char accept = 0;
  851.  
  852.     len = *length;
  853.     if(seg->flags.syn)
  854.         len++;
  855.     if(seg->flags.fin)
  856.         len++;
  857.  
  858.     /* Acceptability tests */
  859.     if(tcb->rcv.wnd == 0){
  860.         /* Only in-order, zero-length segments are acceptable when
  861.          * our window is closed.
  862.          */
  863.         if(seg->seq == tcb->rcv.nxt && len == 0){
  864.             return 0;    /* Acceptable, no trimming needed */
  865.         }
  866.     } else {
  867.         /* Some part of the segment must be in the window */
  868.         if(in_window(tcb,seg->seq)){
  869.             accept++;    /* Beginning is */
  870.         } else if(len != 0){
  871.             if(in_window(tcb,(int32)(seg->seq+len-1)) || /* End is */
  872.              seq_within(tcb->rcv.nxt,seg->seq,(int32)(seg->seq+len-1))){ /* Straddles */
  873.                 accept++;
  874.             }
  875.         }
  876.     }
  877.     if(!accept){
  878.         tcb->rerecv += len;    /* Assume all of it was a duplicate */
  879.         free_p(*bpp);
  880.         return -1;
  881.     }
  882.     if((dupcnt = tcb->rcv.nxt - seg->seq) > 0){
  883.         tcb->rerecv += dupcnt;
  884.         /* Trim off SYN if present */
  885.         if(seg->flags.syn){
  886.             /* SYN is before first data byte */
  887.             seg->flags.syn = 0;
  888.             seg->seq++;
  889.             dupcnt--;
  890.         }
  891.         if(dupcnt > 0){
  892.             pullup(bpp,NULLCHAR,(int16)dupcnt);
  893.             seg->seq += dupcnt;
  894.             *length -= dupcnt;
  895.         }
  896.     }
  897.     if((excess = seg->seq + *length - (tcb->rcv.nxt + tcb->rcv.wnd)) > 0){
  898.         tcb->rerecv += excess;
  899.         /* Trim right edge */
  900.         *length -= excess;
  901.         trim_mbuf(bpp,*length);
  902.         seg->flags.fin = 0;    /* FIN follows last data byte */
  903.     }
  904.     return 0;
  905. }
  906.