src/internet-node/tcp-socket-impl.cc
changeset 3894 6b3415c550e1
parent 3893 94f771c1373a
parent 3261 b0987a6a74c8
child 3895 b584563a7781
equal deleted inserted replaced
3893:94f771c1373a 3894:6b3415c550e1
     1 /* -*-  Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
       
     2 /*
       
     3  * Copyright (c) 2007 Georgia Tech Research Corporation
       
     4  *
       
     5  * This program is free software; you can redistribute it and/or modify
       
     6  * it under the terms of the GNU General Public License version 2 as
       
     7  * published by the Free Software Foundation;
       
     8  *
       
     9  * This program is distributed in the hope that it will be useful,
       
    10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
       
    11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
       
    12  * GNU General Public License for more details.
       
    13  *
       
    14  * You should have received a copy of the GNU General Public License
       
    15  * along with this program; if not, write to the Free Software
       
    16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
       
    17  *
       
    18  * Author: Raj Bhattacharjea <raj.b@gatech.edu>
       
    19  */
       
    20 
       
    21 
       
    22 #include "ns3/node.h"
       
    23 #include "ns3/inet-socket-address.h"
       
    24 #include "ns3/log.h"
       
    25 #include "ns3/ipv4.h"
       
    26 #include "tcp-socket-impl.h"
       
    27 #include "tcp-l4-protocol.h"
       
    28 #include "ipv4-end-point.h"
       
    29 #include "ipv4-l4-demux.h"
       
    30 #include "ns3/simulation-singleton.h"
       
    31 #include "tcp-typedefs.h"
       
    32 #include "ns3/simulator.h"
       
    33 #include "ns3/packet.h"
       
    34 #include "ns3/uinteger.h"
       
    35 #include "ns3/trace-source-accessor.h"
       
    36 
       
    37 #include <algorithm>
       
    38 
       
    39 NS_LOG_COMPONENT_DEFINE ("TcpSocketImpl");
       
    40 
       
    41 using namespace std;
       
    42 
       
    43 namespace ns3 {
       
    44 
       
    45 NS_OBJECT_ENSURE_REGISTERED (TcpSocketImpl);
       
    46 
       
    47 TypeId
       
    48 TcpSocketImpl::GetTypeId ()
       
    49 {
       
    50   static TypeId tid = TypeId("ns3::TcpSocketImpl")
       
    51     .SetParent<TcpSocket> ()
       
    52     .AddTraceSource ("CongestionWindow",
       
    53                      "The TCP connection's congestion window",
       
    54                      MakeTraceSourceAccessor (&TcpSocketImpl::m_cWnd))
       
    55     ;
       
    56   return tid;
       
    57 }
       
    58 
       
    59   TcpSocketImpl::TcpSocketImpl ()
       
    60   : m_skipRetxResched (false),
       
    61     m_dupAckCount (0),
       
    62     m_delAckCount (0),
       
    63     m_endPoint (0),
       
    64     m_node (0),
       
    65     m_tcp (0),
       
    66     m_errno (ERROR_NOTERROR),
       
    67     m_shutdownSend (false),
       
    68     m_shutdownRecv (false),
       
    69     m_connected (false),
       
    70     m_state (CLOSED),
       
    71     m_closeNotified (false),
       
    72     m_closeRequestNotified (false),
       
    73     m_closeOnEmpty (false),
       
    74     m_pendingClose (false),
       
    75     m_nextTxSequence (0),
       
    76     m_highTxMark (0),
       
    77     m_highestRxAck (0),
       
    78     m_lastRxAck (0),
       
    79     m_nextRxSequence (0),
       
    80     m_pendingData (0),
       
    81     m_rtt (0),
       
    82     m_lastMeasuredRtt (Seconds(0.0)),
       
    83     m_rxAvailable (0), 
       
    84     m_wouldBlock (false) 
       
    85 {
       
    86   NS_LOG_FUNCTION (this);
       
    87 }
       
    88 
       
    89 TcpSocketImpl::TcpSocketImpl(const TcpSocketImpl& sock)
       
    90   : TcpSocket(sock), //copy the base class callbacks
       
    91     m_skipRetxResched (sock.m_skipRetxResched),
       
    92     m_dupAckCount (sock.m_dupAckCount),
       
    93     m_delAckCount (0),
       
    94     m_delAckMaxCount (sock.m_delAckMaxCount),
       
    95     m_delAckTimeout (sock.m_delAckTimeout),
       
    96     m_endPoint (0),
       
    97     m_node (sock.m_node),
       
    98     m_tcp (sock.m_tcp),
       
    99     m_remoteAddress (sock.m_remoteAddress),
       
   100     m_remotePort (sock.m_remotePort),
       
   101     m_localAddress (sock.m_localAddress),
       
   102     m_localPort (sock.m_localPort),
       
   103     m_errno (sock.m_errno),
       
   104     m_shutdownSend (sock.m_shutdownSend),
       
   105     m_shutdownRecv (sock.m_shutdownRecv),
       
   106     m_connected (sock.m_connected),
       
   107     m_state (sock.m_state),
       
   108     m_closeNotified (sock.m_closeNotified),
       
   109     m_closeRequestNotified (sock.m_closeRequestNotified),
       
   110     m_closeOnEmpty (sock.m_closeOnEmpty),
       
   111     m_pendingClose (sock.m_pendingClose),
       
   112     m_nextTxSequence (sock.m_nextTxSequence),
       
   113     m_highTxMark (sock.m_highTxMark),
       
   114     m_highestRxAck (sock.m_highestRxAck),
       
   115     m_lastRxAck (sock.m_lastRxAck),
       
   116     m_nextRxSequence (sock.m_nextRxSequence),
       
   117     m_pendingData (0),
       
   118     m_segmentSize (sock.m_segmentSize),
       
   119     m_rxWindowSize (sock.m_rxWindowSize),
       
   120     m_advertisedWindowSize (sock.m_advertisedWindowSize),
       
   121     m_cWnd (sock.m_cWnd),
       
   122     m_ssThresh (sock.m_ssThresh),
       
   123     m_initialCWnd (sock.m_initialCWnd),
       
   124     m_rtt (0),
       
   125     m_lastMeasuredRtt (Seconds(0.0)),
       
   126     m_cnTimeout (sock.m_cnTimeout),
       
   127     m_cnCount (sock.m_cnCount),
       
   128     m_rxAvailable (0),
       
   129     m_wouldBlock (false),
       
   130     m_sndBufSize (sock.m_sndBufSize)
       
   131 {
       
   132   NS_LOG_FUNCTION_NOARGS ();
       
   133   NS_LOG_LOGIC("Invoked the copy constructor");
       
   134   //copy the pending data if necessary
       
   135   if(sock.m_pendingData)
       
   136     {
       
   137       m_pendingData = sock.m_pendingData->Copy();
       
   138     }
       
   139   //copy the rtt if necessary
       
   140   if (sock.m_rtt)
       
   141     {
       
   142       m_rtt = sock.m_rtt->Copy();
       
   143     }
       
   144   //can't "copy" the endpoint just yes, must do this when we know the peer info
       
   145   //too; this is in SYN_ACK_TX
       
   146 }
       
   147 
       
   148 TcpSocketImpl::~TcpSocketImpl ()
       
   149 {
       
   150   NS_LOG_FUNCTION(this);
       
   151   m_node = 0;
       
   152   if (m_endPoint != 0)
       
   153     {
       
   154       NS_ASSERT (m_tcp != 0);
       
   155       /**
       
   156        * Note that this piece of code is a bit tricky:
       
   157        * when DeAllocate is called, it will call into
       
   158        * Ipv4EndPointDemux::Deallocate which triggers
       
   159        * a delete of the associated endPoint which triggers
       
   160        * in turn a call to the method ::Destroy below
       
   161        * will will zero the m_endPoint field.
       
   162        */
       
   163       NS_ASSERT (m_endPoint != 0);
       
   164       m_tcp->DeAllocate (m_endPoint);
       
   165       NS_ASSERT (m_endPoint == 0);
       
   166     }
       
   167   m_tcp = 0;
       
   168   delete m_pendingData; //prevents leak
       
   169   m_pendingData = 0;
       
   170 }
       
   171 
       
   172 void
       
   173 TcpSocketImpl::SetNode (Ptr<Node> node)
       
   174 {
       
   175   m_node = node;
       
   176   // Initialize some variables 
       
   177   m_cWnd = m_initialCWnd * m_segmentSize;
       
   178   m_rxWindowSize = m_advertisedWindowSize;
       
   179 }
       
   180 
       
   181 void 
       
   182 TcpSocketImpl::SetTcp (Ptr<TcpL4Protocol> tcp)
       
   183 {
       
   184   m_tcp = tcp;
       
   185 }
       
   186 void 
       
   187 TcpSocketImpl::SetRtt (Ptr<RttEstimator> rtt)
       
   188 {
       
   189   m_rtt = rtt;
       
   190 }
       
   191 
       
   192 
       
   193 enum Socket::SocketErrno
       
   194 TcpSocketImpl::GetErrno (void) const
       
   195 {
       
   196   NS_LOG_FUNCTION_NOARGS ();
       
   197   return m_errno;
       
   198 }
       
   199 
       
   200 Ptr<Node>
       
   201 TcpSocketImpl::GetNode (void) const
       
   202 {
       
   203   NS_LOG_FUNCTION_NOARGS ();
       
   204   return m_node;
       
   205 }
       
   206 
       
   207 void 
       
   208 TcpSocketImpl::Destroy (void)
       
   209 {
       
   210   NS_LOG_FUNCTION_NOARGS ();
       
   211   m_node = 0;
       
   212   m_endPoint = 0;
       
   213   m_tcp = 0;
       
   214   m_retxEvent.Cancel ();
       
   215 }
       
   216 int
       
   217 TcpSocketImpl::FinishBind (void)
       
   218 {
       
   219   NS_LOG_FUNCTION_NOARGS ();
       
   220   if (m_endPoint == 0)
       
   221     {
       
   222       return -1;
       
   223     }
       
   224   m_endPoint->SetRxCallback (MakeCallback (&TcpSocketImpl::ForwardUp, Ptr<TcpSocketImpl>(this)));
       
   225   m_endPoint->SetDestroyCallback (MakeCallback (&TcpSocketImpl::Destroy, Ptr<TcpSocketImpl>(this)));
       
   226   m_localAddress = m_endPoint->GetLocalAddress ();
       
   227   m_localPort = m_endPoint->GetLocalPort ();
       
   228   return 0;
       
   229 }
       
   230 
       
   231 int
       
   232 TcpSocketImpl::Bind (void)
       
   233 {
       
   234   NS_LOG_FUNCTION_NOARGS ();
       
   235   m_endPoint = m_tcp->Allocate ();
       
   236   return FinishBind ();
       
   237 }
       
   238 int 
       
   239 TcpSocketImpl::Bind (const Address &address)
       
   240 {
       
   241   NS_LOG_FUNCTION (this<<address);
       
   242   if (!InetSocketAddress::IsMatchingType (address))
       
   243     {
       
   244       return ERROR_INVAL;
       
   245     }
       
   246   InetSocketAddress transport = InetSocketAddress::ConvertFrom (address);
       
   247   Ipv4Address ipv4 = transport.GetIpv4 ();
       
   248   uint16_t port = transport.GetPort ();
       
   249   if (ipv4 == Ipv4Address::GetAny () && port == 0)
       
   250     {
       
   251       m_endPoint = m_tcp->Allocate ();
       
   252       NS_LOG_LOGIC ("TcpSocketImpl "<<this<<" got an endpoint: "<<m_endPoint);
       
   253     }
       
   254   else if (ipv4 == Ipv4Address::GetAny () && port != 0)
       
   255     {
       
   256       m_endPoint = m_tcp->Allocate (port);
       
   257       NS_LOG_LOGIC ("TcpSocketImpl "<<this<<" got an endpoint: "<<m_endPoint);
       
   258     }
       
   259   else if (ipv4 != Ipv4Address::GetAny () && port == 0)
       
   260     {
       
   261       m_endPoint = m_tcp->Allocate (ipv4);
       
   262       NS_LOG_LOGIC ("TcpSocketImpl "<<this<<" got an endpoint: "<<m_endPoint);
       
   263     }
       
   264   else if (ipv4 != Ipv4Address::GetAny () && port != 0)
       
   265     {
       
   266       m_endPoint = m_tcp->Allocate (ipv4, port);
       
   267       NS_LOG_LOGIC ("TcpSocketImpl "<<this<<" got an endpoint: "<<m_endPoint);
       
   268     }
       
   269 
       
   270   return FinishBind ();
       
   271 }
       
   272 
       
   273 int 
       
   274 TcpSocketImpl::ShutdownSend (void)
       
   275 {
       
   276   NS_LOG_FUNCTION_NOARGS ();
       
   277   m_shutdownSend = true;
       
   278   return 0;
       
   279 }
       
   280 int 
       
   281 TcpSocketImpl::ShutdownRecv (void)
       
   282 {
       
   283   NS_LOG_FUNCTION_NOARGS ();
       
   284   m_shutdownRecv = false;
       
   285   return 0;
       
   286 }
       
   287 
       
   288 int
       
   289 TcpSocketImpl::Close (void)
       
   290 {
       
   291   NS_LOG_FUNCTION_NOARGS ();
       
   292   if (m_state == CLOSED) 
       
   293     {
       
   294       return -1;
       
   295     }
       
   296   if (m_pendingData && m_pendingData->Size() != 0)
       
   297     { // App close with pending data must wait until all data transmitted
       
   298       m_closeOnEmpty = true;
       
   299       NS_LOG_LOGIC("Socket " << this << 
       
   300                    " deferring close, state " << m_state);
       
   301       return 0;
       
   302     }
       
   303 
       
   304   Actions_t action  = ProcessEvent (APP_CLOSE);
       
   305   ProcessAction (action);
       
   306   ShutdownSend ();
       
   307   return 0;
       
   308 }
       
   309 
       
   310 int
       
   311 TcpSocketImpl::Connect (const Address & address)
       
   312 {
       
   313   NS_LOG_FUNCTION (this << address);
       
   314   if (m_endPoint == 0)
       
   315     {
       
   316       if (Bind () == -1)
       
   317         {
       
   318           NS_ASSERT (m_endPoint == 0);
       
   319           return -1;
       
   320         }
       
   321       NS_ASSERT (m_endPoint != 0);
       
   322     }
       
   323   InetSocketAddress transport = InetSocketAddress::ConvertFrom (address);
       
   324   m_remoteAddress = transport.GetIpv4 ();
       
   325   m_remotePort = transport.GetPort ();
       
   326   
       
   327   uint32_t localIfIndex;
       
   328   Ptr<Ipv4> ipv4 = m_node->GetObject<Ipv4> ();
       
   329 
       
   330   if (ipv4->GetIfIndexForDestination (m_remoteAddress, localIfIndex))
       
   331     {
       
   332       m_endPoint->SetLocalAddress (ipv4->GetAddress (localIfIndex));
       
   333     }
       
   334   else
       
   335     {
       
   336       m_errno = ERROR_NOROUTETOHOST;
       
   337       return -1;
       
   338     }
       
   339 
       
   340   Actions_t action = ProcessEvent (APP_CONNECT);
       
   341   bool success = ProcessAction (action);
       
   342   if (success) 
       
   343     {
       
   344       return 0;
       
   345     }
       
   346   return -1;
       
   347 }
       
   348 int 
       
   349 TcpSocketImpl::Send (const Ptr<Packet> p) //p here is just data, no headers
       
   350 { // TCP Does not deal with packets from app, just data
       
   351   return Send(p->PeekData(), p->GetSize());
       
   352 }
       
   353 
       
   354 int TcpSocketImpl::Send (const uint8_t* buf, uint32_t size)
       
   355 {
       
   356   NS_LOG_FUNCTION (this << buf << size);
       
   357   if (m_state == ESTABLISHED || m_state == SYN_SENT || m_state == CLOSE_WAIT)
       
   358     { 
       
   359       if (size > GetTxAvailable ())
       
   360         {
       
   361           m_wouldBlock = true;
       
   362           m_errno = ERROR_MSGSIZE;
       
   363           return -1;
       
   364         }
       
   365       if (!m_pendingData)
       
   366         {
       
   367           m_pendingData = new PendingData ();   // Create if non-existent
       
   368           m_firstPendingSequence = m_nextTxSequence; // Note seq of first
       
   369         }
       
   370       //PendingData::Add always copies the data buffer, never modifies
       
   371       m_pendingData->Add (size,buf);
       
   372       NS_LOG_DEBUG("TcpSock::Send, pdsize " << m_pendingData->Size() << 
       
   373                    " state " << m_state);
       
   374       Actions_t action = ProcessEvent (APP_SEND);
       
   375       NS_LOG_DEBUG(" action " << action);
       
   376       if (!ProcessAction (action)) 
       
   377         {
       
   378           return -1; // Failed, return zero
       
   379         }
       
   380       return size;
       
   381     }
       
   382   else
       
   383   {
       
   384     m_errno = ERROR_NOTCONN;
       
   385     return -1;
       
   386   }
       
   387 }
       
   388 
       
   389 int TcpSocketImpl::DoSendTo (Ptr<Packet> p, const Address &address)
       
   390 {
       
   391   NS_LOG_FUNCTION (this << p << address);
       
   392   InetSocketAddress transport = InetSocketAddress::ConvertFrom (address);
       
   393   Ipv4Address ipv4 = transport.GetIpv4 ();
       
   394   uint16_t port = transport.GetPort ();
       
   395   return DoSendTo (p, ipv4, port);
       
   396 }
       
   397 
       
   398 int TcpSocketImpl::DoSendTo (Ptr<Packet> p, Ipv4Address ipv4, uint16_t port)
       
   399 {
       
   400   NS_LOG_FUNCTION (this << p << ipv4 << port);
       
   401   if (m_endPoint == 0)
       
   402     {
       
   403       if (Bind () == -1)
       
   404 	{
       
   405           NS_ASSERT (m_endPoint == 0);
       
   406 	  return -1;
       
   407 	}
       
   408       NS_ASSERT (m_endPoint != 0);
       
   409     }
       
   410   if (m_shutdownSend)
       
   411     {
       
   412       m_errno = ERROR_SHUTDOWN;
       
   413       return -1;
       
   414     }
       
   415   m_tcp->Send (p, m_endPoint->GetLocalAddress (), ipv4,
       
   416                   m_endPoint->GetLocalPort (), port);
       
   417   NotifyDataSent (p->GetSize ());
       
   418   return 0;
       
   419 }
       
   420 
       
   421 int 
       
   422 TcpSocketImpl::SendTo (Ptr<Packet> p, const Address &address)
       
   423 {
       
   424   NS_LOG_FUNCTION (this << address << p);
       
   425   if (!m_connected)
       
   426     {
       
   427       m_errno = ERROR_NOTCONN;
       
   428       return -1;
       
   429     }
       
   430   else
       
   431     {
       
   432       return Send (p); //drop the address according to BSD manpages
       
   433     }
       
   434 }
       
   435 
       
   436 uint32_t
       
   437 TcpSocketImpl::GetTxAvailable (void) const
       
   438 {
       
   439   NS_LOG_FUNCTION_NOARGS ();
       
   440   if (m_pendingData != 0)
       
   441     {
       
   442       uint32_t unAckedDataSize = 
       
   443         m_pendingData->SizeFromSeq (m_firstPendingSequence, m_highestRxAck);
       
   444       NS_ASSERT (m_sndBufSize >= unAckedDataSize); //else a logical error
       
   445       return m_sndBufSize-unAckedDataSize;
       
   446     }
       
   447   else
       
   448     {
       
   449       return m_sndBufSize;
       
   450     }
       
   451 }
       
   452 
       
   453 int
       
   454 TcpSocketImpl::Listen (uint32_t q)
       
   455 {
       
   456   NS_LOG_FUNCTION (this << q);
       
   457   Actions_t action = ProcessEvent (APP_LISTEN);
       
   458   ProcessAction (action);
       
   459   return 0;
       
   460 }
       
   461 
       
   462 Ptr<Packet>
       
   463 TcpSocketImpl::Recv (uint32_t maxSize, uint32_t flags)
       
   464 {
       
   465   NS_LOG_FUNCTION_NOARGS ();
       
   466   if (m_deliveryQueue.empty() )
       
   467     {
       
   468       return 0;
       
   469     }
       
   470   Ptr<Packet> p = m_deliveryQueue.front ();
       
   471   if (p->GetSize () <= maxSize)
       
   472     {
       
   473       m_deliveryQueue.pop ();
       
   474       m_rxAvailable -= p->GetSize ();
       
   475     }
       
   476   else
       
   477     {
       
   478       p = 0;
       
   479     }
       
   480   return p;
       
   481 }
       
   482 
       
   483 uint32_t
       
   484 TcpSocketImpl::GetRxAvailable (void) const
       
   485 {
       
   486   NS_LOG_FUNCTION_NOARGS ();
       
   487   // We separately maintain this state to avoid walking the queue 
       
   488   // every time this might be called
       
   489   return m_rxAvailable;
       
   490 }
       
   491 
       
   492 void
       
   493 TcpSocketImpl::ForwardUp (Ptr<Packet> packet, Ipv4Address ipv4, uint16_t port)
       
   494 {
       
   495   NS_LOG_DEBUG("Socket " << this << " got forward up" <<
       
   496                " dport " << m_endPoint->GetLocalPort() <<
       
   497                " daddr " << m_endPoint->GetLocalAddress() <<
       
   498                " sport " << m_endPoint->GetPeerPort() <<
       
   499                " saddr " << m_endPoint->GetPeerAddress());
       
   500 
       
   501   NS_LOG_FUNCTION (this << packet << ipv4 << port);
       
   502   if (m_shutdownRecv)
       
   503     {
       
   504       return;
       
   505     }
       
   506   TcpHeader tcpHeader;
       
   507   packet->RemoveHeader (tcpHeader);
       
   508 
       
   509   if (tcpHeader.GetFlags () & TcpHeader::ACK)
       
   510     {
       
   511       Time m = m_rtt->AckSeq (tcpHeader.GetAckNumber () );
       
   512       if (m != Seconds (0.0))
       
   513         {
       
   514           m_lastMeasuredRtt = m;
       
   515         }
       
   516     }
       
   517 
       
   518   Events_t event = SimulationSingleton<TcpStateMachine>::Get ()->FlagsEvent (tcpHeader.GetFlags () );
       
   519   Actions_t action = ProcessEvent (event); //updates the state
       
   520   Address address = InetSocketAddress (ipv4, port);
       
   521   NS_LOG_DEBUG("Socket " << this << 
       
   522                " processing pkt action, " << action <<
       
   523                " current state " << m_state);
       
   524   ProcessPacketAction (action, packet, tcpHeader, address);
       
   525 }
       
   526 
       
   527 Actions_t TcpSocketImpl::ProcessEvent (Events_t e)
       
   528 {
       
   529   NS_LOG_FUNCTION (this << e);
       
   530   States_t saveState = m_state;
       
   531   NS_LOG_LOGIC ("TcpSocketImpl " << this << " processing event " << e);
       
   532   // simulation singleton is a way to get a single global static instance of a
       
   533   // class intended to be a singleton; see simulation-singleton.h
       
   534   SA stateAction = SimulationSingleton<TcpStateMachine>::Get ()->Lookup (m_state,e);
       
   535   // debug
       
   536   if (stateAction.action == RST_TX)
       
   537     {
       
   538       NS_LOG_LOGIC ("TcpSocketImpl " << this << " sending RST from state "
       
   539               << saveState << " event " << e);
       
   540     }
       
   541   bool needCloseNotify = (stateAction.state == CLOSED && m_state != CLOSED 
       
   542     && e != TIMEOUT);
       
   543   m_state = stateAction.state;
       
   544   NS_LOG_LOGIC ("TcpSocketImpl " << this << " moved from state " << saveState 
       
   545     << " to state " <<m_state);
       
   546   NS_LOG_LOGIC ("TcpSocketImpl " << this << " pendingData " << m_pendingData);
       
   547 
       
   548   //extra event logic is here for RX events
       
   549   //e = SYN_ACK_RX
       
   550   if (saveState == SYN_SENT && m_state == ESTABLISHED)
       
   551     // this means the application side has completed its portion of 
       
   552     // the handshaking
       
   553     {
       
   554       Simulator::ScheduleNow(&TcpSocketImpl::ConnectionSucceeded, this);
       
   555       //NotifyConnectionSucceeded ();
       
   556       m_connected = true;
       
   557       m_endPoint->SetPeer (m_remoteAddress, m_remotePort);
       
   558       NS_LOG_LOGIC ("TcpSocketImpl " << this << " Connected!");
       
   559     }
       
   560 
       
   561   if (needCloseNotify && !m_closeNotified)
       
   562     {
       
   563       NS_LOG_LOGIC ("TcpSocketImpl " << this << " transition to CLOSED from " 
       
   564                << m_state << " event " << e << " closeNot " << m_closeNotified
       
   565                << " action " << stateAction.action);
       
   566       NotifyCloseCompleted ();
       
   567       m_closeNotified = true;
       
   568       NS_LOG_LOGIC ("TcpSocketImpl " << this << " calling Closed from PE"
       
   569               << " origState " << saveState
       
   570               << " event " << e);
       
   571       NS_LOG_LOGIC ("TcpSocketImpl " << this << " transition to CLOSED from "
       
   572           << m_state << " event " << e
       
   573           << " set CloseNotif ");
       
   574     }
       
   575   return stateAction.action;
       
   576 }
       
   577 
       
   578 void TcpSocketImpl::SendEmptyPacket (uint8_t flags)
       
   579 {
       
   580   NS_LOG_FUNCTION (this << flags);
       
   581   Ptr<Packet> p = Create<Packet> ();
       
   582   TcpHeader header;
       
   583 
       
   584   header.SetFlags (flags);
       
   585   header.SetSequenceNumber (m_nextTxSequence);
       
   586   header.SetAckNumber (m_nextRxSequence);
       
   587   header.SetSourcePort (m_endPoint->GetLocalPort ());
       
   588   header.SetDestinationPort (m_remotePort);
       
   589   header.SetWindowSize (m_advertisedWindowSize);
       
   590   m_tcp->SendPacket (p, header, m_endPoint->GetLocalAddress (), 
       
   591     m_remoteAddress);
       
   592   Time rto = m_rtt->RetransmitTimeout ();
       
   593   if (flags & TcpHeader::SYN)
       
   594     {
       
   595       rto = m_cnTimeout;
       
   596       m_cnTimeout = m_cnTimeout + m_cnTimeout;
       
   597       m_cnCount--;
       
   598     }
       
   599   if (m_retxEvent.IsExpired () ) //no outstanding timer
       
   600   {
       
   601     NS_LOG_LOGIC ("Schedule retransmission timeout at time " 
       
   602           << Simulator::Now ().GetSeconds () << " to expire at time " 
       
   603           << (Simulator::Now () + rto).GetSeconds ());
       
   604     m_retxEvent = Simulator::Schedule (rto, &TcpSocketImpl::ReTxTimeout, this);
       
   605   }
       
   606 }
       
   607 
       
   608 bool TcpSocketImpl::ProcessAction (Actions_t a)
       
   609 { // These actions do not require a packet or any TCP Headers
       
   610   NS_LOG_FUNCTION (this << a);
       
   611   switch (a)
       
   612   {
       
   613     case NO_ACT:
       
   614       NS_LOG_LOGIC ("TcpSocketImpl " << this <<" Action: NO_ACT");
       
   615       break;
       
   616     case ACK_TX:
       
   617       SendEmptyPacket (TcpHeader::ACK);
       
   618       break;
       
   619     case ACK_TX_1:
       
   620       NS_ASSERT (false); // This should be processed in ProcessPacketAction
       
   621       break;
       
   622     case RST_TX:
       
   623       NS_LOG_LOGIC ("TcpSocketImpl " << this <<" Action RST_TX");
       
   624       SendEmptyPacket (TcpHeader::RST);
       
   625       break;
       
   626     case SYN_TX:
       
   627       NS_LOG_LOGIC ("TcpSocketImpl " << this <<" Action SYN_TX");
       
   628       // TCP SYN Flag consumes one byte
       
   629       // is the above correct? we're SENDING a syn, not acking back -- Raj
       
   630       // commented out for now
       
   631       // m_nextTxSequence+= 1;
       
   632       SendEmptyPacket (TcpHeader::SYN);
       
   633       break;
       
   634     case SYN_ACK_TX:
       
   635       NS_LOG_LOGIC ("TcpSocketImpl " << this <<" Action SYN_ACK_TX");
       
   636       // TCP SYN Flag consumes one byte
       
   637       ++m_nextRxSequence;
       
   638       SendEmptyPacket (TcpHeader::SYN | TcpHeader::ACK);
       
   639       break;
       
   640     case FIN_TX:
       
   641       NS_LOG_LOGIC ("TcpSocketImpl " << this <<" Action FIN_TX");
       
   642       SendEmptyPacket (TcpHeader::FIN);
       
   643       break;
       
   644     case FIN_ACK_TX:
       
   645       NS_LOG_LOGIC ("TcpSocketImpl " << this <<" Action FIN_ACK_TX");
       
   646       SendEmptyPacket (TcpHeader::FIN | TcpHeader::ACK);
       
   647       break;
       
   648     case NEW_ACK:
       
   649       NS_ASSERT (false); // This should be processed in ProcessPacketAction
       
   650       break;
       
   651     case NEW_SEQ_RX:
       
   652       NS_ASSERT (false); // This should be processed in ProcessPacketAction
       
   653       break;
       
   654     case RETX:
       
   655       NS_LOG_LOGIC ("TcpSocketImpl " << this <<" Action RETX");
       
   656       break;
       
   657     case TX_DATA:
       
   658       NS_LOG_LOGIC ("TcpSocketImpl " << this <<" Action TX_DATA");
       
   659       SendPendingData ();
       
   660       break;
       
   661     case PEER_CLOSE:
       
   662       NS_ASSERT (false); // This should be processed in ProcessPacketAction
       
   663       NS_LOG_LOGIC ("TcpSocketImpl " << this <<" Action PEER_CLOSE");
       
   664       break;
       
   665     case APP_CLOSED:
       
   666       NS_LOG_LOGIC ("TcpSocketImpl " << this <<" Action APP_CLOSED");
       
   667       break;
       
   668     case CANCEL_TM:
       
   669       NS_LOG_LOGIC ("TcpSocketImpl " << this <<" Action CANCEL_TM");
       
   670       break;
       
   671     case APP_NOTIFY:
       
   672       NS_LOG_LOGIC ("TcpSocketImpl " << this <<" Action APP_NOTIFY");
       
   673       break;
       
   674     case SERV_NOTIFY:
       
   675       NS_ASSERT (false); // This should be processed in ProcessPacketAction
       
   676       break;
       
   677     case LAST_ACTION:
       
   678       NS_LOG_LOGIC ("TcpSocketImpl " << this <<" Action LAST_ACTION");
       
   679       break;
       
   680   }
       
   681   return true;
       
   682 }
       
   683 
       
   684 bool TcpSocketImpl::ProcessPacketAction (Actions_t a, Ptr<Packet> p,
       
   685                                      const TcpHeader& tcpHeader,
       
   686                                      const Address& fromAddress)
       
   687 {
       
   688   NS_LOG_FUNCTION (this << a << p  << fromAddress);
       
   689   uint32_t localIfIndex;
       
   690   Ptr<Ipv4> ipv4 = m_node->GetObject<Ipv4> ();
       
   691   switch (a)
       
   692   {
       
   693     case SYN_ACK_TX:
       
   694       NS_LOG_LOGIC ("TcpSocketImpl " << this <<" Action SYN_ACK_TX");
       
   695 //      m_remotePort = InetSocketAddress::ConvertFrom (fromAddress).GetPort ();
       
   696 //      m_remoteAddress = InetSocketAddress::ConvertFrom (fromAddress).GetIpv4 ();
       
   697 //       if (ipv4->GetIfIndexForDestination (m_remoteAddress, localIfIndex))
       
   698 //         {
       
   699 //           m_localAddress = ipv4->GetAddress (localIfIndex);
       
   700 //         }
       
   701       if (m_state == LISTEN) //this means we should fork a new TcpSocketImpl
       
   702         {
       
   703           NS_LOG_DEBUG("In SYN_ACK_TX, m_state is LISTEN, this " << this);
       
   704           //notify the server that we got a SYN
       
   705           // If server refuses connection do nothing
       
   706           if (!NotifyConnectionRequest(fromAddress)) return true;
       
   707           // Clone the socket
       
   708           Ptr<TcpSocketImpl> newSock = Copy ();
       
   709           NS_LOG_LOGIC ("Cloned a TcpSocketImpl " << newSock);
       
   710           //this listening socket should do nothing more
       
   711           Simulator::ScheduleNow (&TcpSocketImpl::CompleteFork, newSock,
       
   712                                   p, tcpHeader,fromAddress);
       
   713           return true;
       
   714         }
       
   715         // This is the cloned endpoint
       
   716         m_endPoint->SetPeer (m_remoteAddress, m_remotePort);
       
   717         if (ipv4->GetIfIndexForDestination (m_remoteAddress, localIfIndex))
       
   718           {
       
   719             m_localAddress = ipv4->GetAddress (localIfIndex);
       
   720             m_endPoint->SetLocalAddress (m_localAddress);
       
   721             // Leave local addr in the portmap to any, as the path from
       
   722             // remote can change and packets can arrive on different interfaces
       
   723             //m_endPoint->SetLocalAddress (Ipv4Address::GetAny());
       
   724           }
       
   725         // TCP SYN consumes one byte
       
   726         m_nextRxSequence = tcpHeader.GetSequenceNumber() + SequenceNumber(1);
       
   727         SendEmptyPacket (TcpHeader::SYN | TcpHeader::ACK);
       
   728       break;
       
   729     case ACK_TX_1:
       
   730       NS_LOG_LOGIC ("TcpSocketImpl " << this <<" Action ACK_TX_1");
       
   731       // TCP SYN consumes one byte
       
   732       m_nextRxSequence = tcpHeader.GetSequenceNumber() + SequenceNumber(1);
       
   733       m_nextTxSequence = tcpHeader.GetAckNumber ();
       
   734       m_firstPendingSequence = m_nextTxSequence;  //bug 166
       
   735       NS_LOG_DEBUG ("TcpSocketImpl " << this << " ACK_TX_1" <<
       
   736                     " nextRxSeq " << m_nextRxSequence);
       
   737       SendEmptyPacket (TcpHeader::ACK);
       
   738       m_rxWindowSize = tcpHeader.GetWindowSize ();
       
   739       if (tcpHeader.GetAckNumber () > m_highestRxAck)
       
   740       {
       
   741         m_highestRxAck = tcpHeader.GetAckNumber ();
       
   742         // Data freed from the send buffer; notify any blocked sender
       
   743         if (m_wouldBlock)
       
   744           {
       
   745             NotifySend (GetTxAvailable ());
       
   746             m_wouldBlock = false;
       
   747           }
       
   748       }
       
   749       SendPendingData ();
       
   750       break;
       
   751     case NEW_ACK:
       
   752       NS_LOG_LOGIC ("TcpSocketImpl " << this <<" Action NEW_ACK_TX");
       
   753       if (tcpHeader.GetAckNumber () < m_highestRxAck) //old ack, do nothing
       
   754       {
       
   755         break;
       
   756       }
       
   757       if (tcpHeader.GetAckNumber () == m_highestRxAck && 
       
   758          tcpHeader.GetAckNumber ()  < m_nextTxSequence)
       
   759       {
       
   760         DupAck (tcpHeader, ++m_dupAckCount);
       
   761         break;
       
   762       }
       
   763       if (tcpHeader.GetAckNumber () > m_highestRxAck)  
       
   764         {
       
   765           m_dupAckCount = 0;
       
   766         }
       
   767       NewAck (tcpHeader.GetAckNumber ());
       
   768       break;
       
   769     case NEW_SEQ_RX:
       
   770       NS_LOG_LOGIC ("TcpSocketImpl " << this <<" Action NEW_SEQ_RX");
       
   771       NewRx (p, tcpHeader, fromAddress); // Process new data received
       
   772       break;
       
   773     case PEER_CLOSE:
       
   774     {
       
   775       // First we have to be sure the FIN packet was not received
       
   776       // out of sequence.  If so, note pending close and process
       
   777       // new sequence rx
       
   778       if (tcpHeader.GetSequenceNumber () != m_nextRxSequence)
       
   779         { // process close later
       
   780           m_pendingClose = true;
       
   781           NS_LOG_LOGIC ("TcpSocketImpl " << this << " setting pendingClose" 
       
   782             << " rxseq " << tcpHeader.GetSequenceNumber () 
       
   783             << " nextRxSeq " << m_nextRxSequence);
       
   784           NewRx (p, tcpHeader, fromAddress);
       
   785           return true;
       
   786         }
       
   787       // Now we need to see if any data came with the FIN
       
   788       // if so, call NewRx
       
   789       if (p->GetSize () != 0)
       
   790         {
       
   791           NewRx (p, tcpHeader, fromAddress);
       
   792         }
       
   793       States_t saveState = m_state; // Used to see if app responds
       
   794       NS_LOG_LOGIC ("TcpSocketImpl " << this 
       
   795           << " peer close, state " << m_state);
       
   796       if (!m_closeRequestNotified)
       
   797         {
       
   798           NS_LOG_LOGIC ("TCP " << this 
       
   799               << " calling AppCloseRequest");
       
   800           NotifyCloseRequested(); 
       
   801           m_closeRequestNotified = true;
       
   802         }
       
   803       NS_LOG_LOGIC ("TcpSocketImpl " << this 
       
   804           << " peer close, state after " << m_state);
       
   805       if (m_state == saveState)
       
   806         { // Need to ack, the application will close later
       
   807           SendEmptyPacket (TcpHeader::ACK);
       
   808 //               // Also need to re-tx the ack if we
       
   809         }
       
   810       if (m_state == LAST_ACK)
       
   811         {
       
   812           NS_LOG_LOGIC ("TcpSocketImpl " << this << " scheduling LATO1");
       
   813           m_lastAckEvent = Simulator::Schedule (m_rtt->RetransmitTimeout (),
       
   814                                                 &TcpSocketImpl::LastAckTimeout,this);
       
   815         }
       
   816       break;
       
   817     }
       
   818     case SERV_NOTIFY:
       
   819       NS_LOG_LOGIC ("TcpSocketImpl " << this <<" Action SERV_NOTIFY");
       
   820       NS_LOG_LOGIC ("TcpSocketImpl " << this << " Connected!");
       
   821       NotifyNewConnectionCreated (this, fromAddress);
       
   822       m_connected = true; // ! This is bogus; fix when we clone the tcp
       
   823       m_endPoint->SetPeer (m_remoteAddress, m_remotePort);
       
   824       //treat the connection orientation final ack as a newack
       
   825       CommonNewAck (tcpHeader.GetAckNumber (), true);
       
   826       break;
       
   827     default:
       
   828       break;
       
   829   }
       
   830   return true;
       
   831 }
       
   832 
       
   833 void TcpSocketImpl::CompleteFork(Ptr<Packet> p, const TcpHeader& h, const Address& fromAddress)
       
   834 {
       
   835   // Get port and address from peer (connecting host)
       
   836   m_remotePort = InetSocketAddress::ConvertFrom (fromAddress).GetPort ();
       
   837   m_remoteAddress = InetSocketAddress::ConvertFrom (fromAddress).GetIpv4 ();
       
   838   m_endPoint = m_tcp->Allocate (m_localAddress,
       
   839                                 m_localPort,
       
   840                                 m_remoteAddress,
       
   841                                 m_remotePort);
       
   842   //the cloned socket with be in listen state, so manually change state
       
   843   m_state = SYN_RCVD;
       
   844   //equivalent to FinishBind
       
   845   m_endPoint->SetRxCallback (MakeCallback (&TcpSocketImpl::ForwardUp, Ptr<TcpSocketImpl>(this)));
       
   846   m_endPoint->SetDestroyCallback (MakeCallback (&TcpSocketImpl::Destroy, Ptr<TcpSocketImpl>(this)));
       
   847   ProcessPacketAction(SYN_ACK_TX, p, h, fromAddress);
       
   848  }
       
   849 
       
   850 void TcpSocketImpl::ConnectionSucceeded()
       
   851 { // We would preferred to have scheduled an event directly to
       
   852   // NotifyConnectionSucceeded, but (sigh) these are protected
       
   853   // and we can get the address of it :(
       
   854   NotifyConnectionSucceeded();
       
   855 }
       
   856 
       
   857 bool TcpSocketImpl::SendPendingData (bool withAck)
       
   858 {
       
   859   NS_LOG_FUNCTION (this << withAck);
       
   860   NS_LOG_LOGIC ("ENTERING SendPendingData");
       
   861   if (!m_pendingData)
       
   862     {
       
   863       return false; // No data exists
       
   864     }
       
   865   uint32_t nPacketsSent = 0;
       
   866   while (m_pendingData->SizeFromSeq (m_firstPendingSequence, m_nextTxSequence))
       
   867     {
       
   868       uint32_t w = AvailableWindow ();// Get available window size
       
   869       NS_LOG_LOGIC ("TcpSocketImpl " << this << " SendPendingData"
       
   870            << " w " << w 
       
   871            << " rxwin " << m_rxWindowSize
       
   872            << " cWnd " << m_cWnd
       
   873            << " segsize " << m_segmentSize
       
   874            << " nextTxSeq " << m_nextTxSequence
       
   875            << " highestRxAck " << m_highestRxAck 
       
   876            << " pd->Size " << m_pendingData->Size ()
       
   877            << " pd->SFS " << m_pendingData->SizeFromSeq (m_firstPendingSequence, m_nextTxSequence));
       
   878 
       
   879       if (w < m_segmentSize && m_pendingData->Size () > w)
       
   880         {
       
   881           break; // No more
       
   882         }
       
   883       uint32_t s = std::min (w, m_segmentSize);  // Send no more than window
       
   884       Ptr<Packet> p = m_pendingData->CopyFromSeq (s, m_firstPendingSequence, 
       
   885         m_nextTxSequence);
       
   886       NS_LOG_LOGIC("TcpSocketImpl " << this << " sendPendingData"
       
   887                    << " txseq " << m_nextTxSequence
       
   888                    << " s " << s 
       
   889                    << " datasize " << p->GetSize() );
       
   890       uint8_t flags = 0;
       
   891       if (withAck)
       
   892         {
       
   893           flags |= TcpHeader::ACK;
       
   894         }
       
   895       uint32_t sz = p->GetSize (); // Size of packet
       
   896       uint32_t remainingData = m_pendingData->SizeFromSeq(
       
   897           m_firstPendingSequence,
       
   898           m_nextTxSequence + SequenceNumber (sz));
       
   899       if (m_closeOnEmpty && (remainingData == 0))
       
   900         {
       
   901           flags = TcpHeader::FIN;
       
   902           m_state = FIN_WAIT_1;
       
   903         }
       
   904 
       
   905       TcpHeader header;
       
   906       header.SetFlags (flags);
       
   907       header.SetSequenceNumber (m_nextTxSequence);
       
   908       header.SetAckNumber (m_nextRxSequence);
       
   909       header.SetSourcePort (m_endPoint->GetLocalPort());
       
   910       header.SetDestinationPort (m_remotePort);
       
   911       if (m_shutdownSend)
       
   912         {
       
   913           m_errno = ERROR_SHUTDOWN;
       
   914           return -1;
       
   915         }
       
   916 
       
   917       
       
   918       if (m_retxEvent.IsExpired () ) //go ahead and schedule the retransmit
       
   919         {
       
   920             Time rto = m_rtt->RetransmitTimeout (); 
       
   921             NS_LOG_LOGIC ("Schedule retransmission timeout at time " << 
       
   922               Simulator::Now ().GetSeconds () << " to expire at time " <<
       
   923               (Simulator::Now () + rto).GetSeconds () );
       
   924           m_retxEvent = Simulator::Schedule (rto,&TcpSocketImpl::ReTxTimeout,this);
       
   925         }
       
   926       NS_LOG_LOGIC ("About to send a packet with flags: " << flags);
       
   927       m_tcp->SendPacket (p, header,
       
   928                          m_endPoint->GetLocalAddress (),
       
   929                          m_remoteAddress);
       
   930       m_rtt->SentSeq(m_nextTxSequence, sz);       // notify the RTT
       
   931       // Notify the application
       
   932       Simulator::ScheduleNow(&TcpSocketImpl::NotifyDataSent, this, p->GetSize ());
       
   933       nPacketsSent++;                             // Count sent this loop
       
   934       m_nextTxSequence += sz;                     // Advance next tx sequence
       
   935       // Note the high water mark
       
   936       m_highTxMark = std::max (m_nextTxSequence, m_highTxMark);
       
   937     }
       
   938   NS_LOG_LOGIC ("Sent "<<nPacketsSent<<" packets");
       
   939   NS_LOG_LOGIC("RETURN SendPendingData");
       
   940   return (nPacketsSent>0);
       
   941 }
       
   942 
       
   943 uint32_t  TcpSocketImpl::UnAckDataCount ()
       
   944 {
       
   945   NS_LOG_FUNCTION_NOARGS ();
       
   946   return m_nextTxSequence - m_highestRxAck;
       
   947 }
       
   948 
       
   949 uint32_t  TcpSocketImpl::BytesInFlight ()
       
   950 {
       
   951   NS_LOG_FUNCTION_NOARGS ();
       
   952   return m_highTxMark - m_highestRxAck;
       
   953 }
       
   954 
       
   955 uint32_t  TcpSocketImpl::Window ()
       
   956 {
       
   957   NS_LOG_FUNCTION_NOARGS ();
       
   958   NS_LOG_LOGIC ("TcpSocketImpl::Window() "<<this);
       
   959   return std::min (m_rxWindowSize, m_cWnd.Get());
       
   960 }
       
   961 
       
   962 uint32_t  TcpSocketImpl::AvailableWindow ()
       
   963 {
       
   964   NS_LOG_FUNCTION_NOARGS ();
       
   965   uint32_t unack = UnAckDataCount (); // Number of outstanding bytes
       
   966   uint32_t win = Window ();
       
   967   if (win < unack) 
       
   968     {
       
   969       return 0;  // No space available
       
   970     }
       
   971   return (win - unack);       // Amount of window space available
       
   972 }
       
   973 
       
   974 void TcpSocketImpl::NewRx (Ptr<Packet> p,
       
   975                         const TcpHeader& tcpHeader, 
       
   976                         const Address& fromAddress)
       
   977 {
       
   978   NS_LOG_FUNCTION (this << p << "tcpHeader " << fromAddress);
       
   979   NS_LOG_LOGIC ("TcpSocketImpl " << this << " NewRx,"
       
   980                 << " seq " << tcpHeader.GetSequenceNumber()
       
   981                 << " ack " << tcpHeader.GetAckNumber()
       
   982                 << " p.size is " << p->GetSize () );
       
   983   NS_LOG_DEBUG ("TcpSocketImpl " << this <<
       
   984                 " NewRx," <<
       
   985                 " seq " << tcpHeader.GetSequenceNumber() <<
       
   986                 " ack " << tcpHeader.GetAckNumber() <<
       
   987                 " p.size is " << p->GetSize());
       
   988   States_t origState = m_state;
       
   989   uint32_t s = p->GetSize ();  // Size of associated data
       
   990   if (s == 0)
       
   991     {// Nothing to do if no associated data
       
   992       return;
       
   993     }
       
   994   // Log sequence received if enabled
       
   995   // NoteTimeSeq(LOG_SEQ_RX, h->sequenceNumber);
       
   996   // Three possibilities
       
   997   // 1) Received seq is expected, deliver this and any buffered data
       
   998   // 2) Received seq is < expected, just re-ack previous
       
   999   // 3) Received seq is > expected, just re-ack previous and buffer data
       
  1000   if (tcpHeader.GetSequenceNumber () == m_nextRxSequence)
       
  1001     { // If seq is expected seq
       
  1002       // 1) Update nextRxSeq
       
  1003       // 2) Deliver to application this packet
       
  1004       // 3) See if any buffered can be delivered
       
  1005       // 4) Send the ack
       
  1006       m_nextRxSequence += s;           // Advance next expected sequence
       
  1007       //bytesReceived += s;       // Statistics
       
  1008       NS_LOG_LOGIC("Case 1, advanced nrxs to " << m_nextRxSequence );
       
  1009       SocketRxAddressTag tag;
       
  1010       tag.SetAddress (fromAddress);
       
  1011       p->AddTag (tag);
       
  1012       m_deliveryQueue.push (p);
       
  1013       m_rxAvailable += p->GetSize ();
       
  1014       NotifyDataRecv ();
       
  1015       if (m_closeNotified)
       
  1016         {
       
  1017           NS_LOG_LOGIC ("Tcp " << this << " HuH?  Got data after closeNotif");
       
  1018         }
       
  1019       NS_LOG_LOGIC ("TcpSocketImpl " << this << " adv rxseq by " << s);
       
  1020       // Look for buffered data
       
  1021       UnAckData_t::iterator i;
       
  1022       // Note that the bufferedData list DOES contain the tcp header
       
  1023       while (!m_bufferedData.empty ())
       
  1024         { // Check the buffered data for delivery
       
  1025           NS_LOG_LOGIC("TCP " << this << " bufferedData.size() " 
       
  1026               << m_bufferedData.size () 
       
  1027               << " time " << Simulator::Now ());
       
  1028           i = m_bufferedData.begin ();
       
  1029           Ptr<Packet> p1 = i->second;
       
  1030           SequenceNumber s1 = 0;
       
  1031           if (i->first > m_nextRxSequence) 
       
  1032             {
       
  1033               break;  // Not next expected
       
  1034             }
       
  1035           // already have the header as a param
       
  1036           //TCPHeader* h = dynamic_cast<TCPHeader*>(p1->PopPDU());
       
  1037           // Check non-null here...
       
  1038           uint8_t flags = tcpHeader.GetFlags ();           // Flags (used below)
       
  1039           if (i->first < m_nextRxSequence)
       
  1040             { // remove already delivered data
       
  1041               // Two cases here.
       
  1042               // 1) seq + length <= nextRxSeq, just discard
       
  1043               // 2) seq + length > nextRxSeq, can deliver partial
       
  1044               s1 = p->GetSize ();
       
  1045               if (i->first + s1 < m_nextRxSequence)
       
  1046                 { // Just remove from list
       
  1047                   //bufferedData.erase(i);
       
  1048                   p1 = 0; // Nothing to deliver
       
  1049                 }
       
  1050               else
       
  1051                 { // Remove partial data to prepare for delivery
       
  1052                   uint32_t dup = m_nextRxSequence - i->first;
       
  1053                   i->second = p1->CreateFragment (0, p1->GetSize () - dup);
       
  1054                   p1 = i->second;
       
  1055                 }
       
  1056             }
       
  1057           else
       
  1058             { // At this point i->first must equal nextRxSeq
       
  1059               if (i->first != m_nextRxSequence)
       
  1060                 {
       
  1061                   NS_FATAL_ERROR ("HuH?  NexRx failure, first " 
       
  1062                       << i->first << " nextRxSeq " << m_nextRxSequence);
       
  1063                 }
       
  1064               s1 = p1->GetSize ();
       
  1065             }
       
  1066           SocketRxAddressTag tag;
       
  1067           tag.SetAddress (fromAddress);
       
  1068           p1->AddTag (tag);
       
  1069           m_deliveryQueue.push (p1);
       
  1070           m_rxAvailable += p->GetSize ();
       
  1071           NotifyDataRecv ();
       
  1072 
       
  1073           NS_LOG_LOGIC ("TcpSocketImpl " << this << " adv rxseq1 by " << s1 );
       
  1074           m_nextRxSequence += s1;           // Note data received
       
  1075           m_bufferedData.erase (i);     // Remove from list
       
  1076           if (flags & TcpHeader::FIN)
       
  1077             NS_LOG_LOGIC("TcpSocketImpl " << this 
       
  1078                     << " found FIN in buffered");
       
  1079         }
       
  1080 
       
  1081       if (m_pendingClose || (origState > ESTABLISHED))
       
  1082         { // See if we can close now
       
  1083           if (m_bufferedData.empty())
       
  1084             {
       
  1085               ProcessPacketAction (PEER_CLOSE, p, tcpHeader, fromAddress);
       
  1086             }
       
  1087         }
       
  1088     }
       
  1089   else if (SequenceNumber (tcpHeader.GetSequenceNumber ()) >= m_nextRxSequence)
       
  1090     { // Need to buffer this one
       
  1091       NS_LOG_LOGIC ("Case 2, buffering " << tcpHeader.GetSequenceNumber () );
       
  1092       UnAckData_t::iterator i = 
       
  1093         m_bufferedData.find (tcpHeader.GetSequenceNumber () );
       
  1094       if (i != m_bufferedData.end () )
       
  1095         {
       
  1096           i->second = 0; // relase reference to already buffered
       
  1097         }
       
  1098       // Save for later delivery
       
  1099       m_bufferedData[tcpHeader.GetSequenceNumber () ] = p;  
       
  1100     }
       
  1101   else
       
  1102     { // debug
       
  1103       NS_LOG_LOGIC("TCP " << this 
       
  1104                << " got seq " << tcpHeader.GetSequenceNumber ()
       
  1105                << " expected " << m_nextRxSequence
       
  1106                << "       flags " << tcpHeader.GetFlags ());
       
  1107     }
       
  1108   // Now send a new ack packet acknowledging all received and delivered data
       
  1109   if(++m_delAckCount >= m_delAckMaxCount)
       
  1110   {
       
  1111     m_delAckEvent.Cancel();
       
  1112     m_delAckCount = 0;
       
  1113     SendEmptyPacket (TcpHeader::ACK);
       
  1114   }
       
  1115   else
       
  1116   {
       
  1117     m_delAckEvent = Simulator::Schedule (m_delAckTimeout, &TcpSocketImpl::DelAckTimeout, this);
       
  1118   }
       
  1119 }
       
  1120 
       
  1121 void TcpSocketImpl::DelAckTimeout ()
       
  1122 {
       
  1123   m_delAckCount = 0;
       
  1124   SendEmptyPacket (TcpHeader::ACK);
       
  1125 }
       
  1126 
       
  1127 void TcpSocketImpl::CommonNewAck (SequenceNumber ack, bool skipTimer)
       
  1128 { // CommonNewAck is called only for "New" (non-duplicate) acks
       
  1129   // and MUST be called by any subclass, from the NewAck function
       
  1130   // Always cancel any pending re-tx timer on new acknowledgement
       
  1131   NS_LOG_FUNCTION (this << ack << skipTimer); 
       
  1132   //DEBUG(1,(cout << "TCP " << this << "Cancelling retx timer " << endl));
       
  1133   if (!skipTimer)
       
  1134     {
       
  1135       m_retxEvent.Cancel ();  
       
  1136       //On recieving a "New" ack we restart retransmission timer .. RFC 2988
       
  1137       Time rto = m_rtt->RetransmitTimeout ();
       
  1138       NS_LOG_LOGIC ("Schedule retransmission timeout at time " 
       
  1139           << Simulator::Now ().GetSeconds () << " to expire at time " 
       
  1140           << (Simulator::Now () + rto).GetSeconds ());
       
  1141     m_retxEvent = Simulator::Schedule (rto, &TcpSocketImpl::ReTxTimeout, this);
       
  1142     }
       
  1143   NS_LOG_LOGIC ("TCP " << this << " NewAck " << ack 
       
  1144            << " numberAck " << (ack - m_highestRxAck)); // Number bytes ack'ed
       
  1145   m_highestRxAck = ack;         // Note the highest recieved Ack
       
  1146   if (m_wouldBlock)
       
  1147     {
       
  1148       // m_highestRxAck advancing means some data was acked, and the size 
       
  1149       // of free space in the buffer has increased
       
  1150       NotifySend (GetTxAvailable ());
       
  1151       m_wouldBlock = false;
       
  1152     }
       
  1153   if (ack > m_nextTxSequence) 
       
  1154     {
       
  1155       m_nextTxSequence = ack; // If advanced
       
  1156     }
       
  1157   // See if all pending ack'ed; if so we can delete the data
       
  1158   if (m_pendingData)
       
  1159     { // Data exists, see if can be deleted
       
  1160       if (m_pendingData->SizeFromSeq (m_firstPendingSequence, m_highestRxAck) == 0)
       
  1161         { // All pending acked, can be deleted
       
  1162           m_pendingData->Clear ();
       
  1163           delete m_pendingData;
       
  1164           m_pendingData = 0;
       
  1165           // Insure no re-tx timer
       
  1166           m_retxEvent.Cancel ();
       
  1167         }
       
  1168     }
       
  1169   // Try to send more data
       
  1170   SendPendingData();
       
  1171 }
       
  1172 
       
  1173 Ptr<TcpSocketImpl> TcpSocketImpl::Copy ()
       
  1174 {
       
  1175   return CopyObject<TcpSocketImpl> (this);
       
  1176 }
       
  1177 
       
  1178 void TcpSocketImpl::NewAck (SequenceNumber seq)
       
  1179 { // New acknowledgement up to sequence number "seq"
       
  1180   // Adjust congestion window in response to new ack's received
       
  1181   NS_LOG_FUNCTION (this << seq);
       
  1182   NS_LOG_LOGIC ("TcpSocketImpl " << this << " NewAck "
       
  1183            << " seq " << seq
       
  1184            << " cWnd " << m_cWnd
       
  1185            << " ssThresh " << m_ssThresh);
       
  1186   if (m_cWnd < m_ssThresh)
       
  1187     { // Slow start mode, add one segSize to cWnd
       
  1188       m_cWnd += m_segmentSize;
       
  1189       NS_LOG_LOGIC ("TcpSocketImpl " << this << " NewCWnd SlowStart, cWnd " << m_cWnd 
       
  1190           << " sst " << m_ssThresh);
       
  1191     }
       
  1192   else
       
  1193     { // Congestion avoidance mode, adjust by (ackBytes*segSize) / cWnd
       
  1194       double adder =  ((double) m_segmentSize * m_segmentSize) / m_cWnd.Get();
       
  1195       if (adder < 1.0) 
       
  1196         {
       
  1197           adder = 1.0;
       
  1198         }
       
  1199       m_cWnd += (uint32_t) adder;
       
  1200       NS_LOG_LOGIC ("NewCWnd CongAvoid, cWnd " << m_cWnd 
       
  1201            << " sst " << m_ssThresh);
       
  1202     }
       
  1203   CommonNewAck (seq, false);           // Complete newAck processing
       
  1204 }
       
  1205 
       
  1206 void TcpSocketImpl::DupAck (const TcpHeader& t, uint32_t count)
       
  1207 {
       
  1208   NS_LOG_FUNCTION (this << "t " << count);
       
  1209   NS_LOG_LOGIC ("TcpSocketImpl " << this << " DupAck " <<  t.GetAckNumber ()
       
  1210       << ", count " << count
       
  1211       << ", time " << Simulator::Now ());
       
  1212   if (count == 3)
       
  1213   { // Count of three indicates triple duplicate ack
       
  1214     m_ssThresh = Window () / 2; // Per RFC2581
       
  1215     m_ssThresh = std::max (m_ssThresh, 2 * m_segmentSize);
       
  1216     NS_LOG_LOGIC("TcpSocketImpl " << this << "Tahoe TDA, time " << Simulator::Now ()
       
  1217         << " seq " << t.GetAckNumber ()
       
  1218         << " in flight " << BytesInFlight ()
       
  1219         << " new ssthresh " << m_ssThresh);
       
  1220 
       
  1221     m_cWnd = m_segmentSize; // Collapse cwnd (re-enter slowstart)
       
  1222     // For Tahoe, we also reset nextTxSeq
       
  1223     m_nextTxSequence = m_highestRxAck;
       
  1224     SendPendingData ();
       
  1225   }
       
  1226 }
       
  1227 
       
  1228 void TcpSocketImpl::ReTxTimeout ()
       
  1229 { // Retransmit timeout
       
  1230   NS_LOG_FUNCTION (this);
       
  1231   m_ssThresh = Window () / 2; // Per RFC2581
       
  1232   m_ssThresh = std::max (m_ssThresh, 2 * m_segmentSize);
       
  1233   // Set cWnd to segSize on timeout,  per rfc2581
       
  1234   // Collapse congestion window (re-enter slowstart)
       
  1235   m_cWnd = m_segmentSize;           
       
  1236   m_nextTxSequence = m_highestRxAck; // Start from highest Ack
       
  1237   m_rtt->IncreaseMultiplier (); // DoubleValue timeout value for next retx timer
       
  1238   Retransmit ();             // Retransmit the packet
       
  1239 }
       
  1240 
       
  1241 void TcpSocketImpl::LastAckTimeout ()
       
  1242 {
       
  1243   m_lastAckEvent.Cancel ();
       
  1244   if (m_state == LAST_ACK)
       
  1245     {
       
  1246       Actions_t action = ProcessEvent (TIMEOUT);
       
  1247       ProcessAction (action);
       
  1248     }
       
  1249   if (!m_closeNotified)
       
  1250     {
       
  1251       m_closeNotified = true;
       
  1252     }
       
  1253 }
       
  1254 
       
  1255 void TcpSocketImpl::Retransmit ()
       
  1256 {
       
  1257   NS_LOG_FUNCTION (this);
       
  1258   uint8_t flags = TcpHeader::NONE;
       
  1259   if (m_state == SYN_SENT) 
       
  1260     {
       
  1261       if (m_cnCount > 0) 
       
  1262         {
       
  1263           SendEmptyPacket (TcpHeader::SYN);
       
  1264           return;
       
  1265         }
       
  1266       else
       
  1267         {
       
  1268           NotifyConnectionFailed ();
       
  1269           return;
       
  1270         }
       
  1271     } 
       
  1272   if (!m_pendingData)
       
  1273     {
       
  1274       if (m_state == FIN_WAIT_1 || m_state == FIN_WAIT_2)
       
  1275         { // Must have lost FIN, re-send
       
  1276           SendEmptyPacket (TcpHeader::FIN);
       
  1277         }
       
  1278       return;
       
  1279     }
       
  1280   Ptr<Packet> p = m_pendingData->CopyFromSeq (m_segmentSize,
       
  1281                                             m_firstPendingSequence,
       
  1282                                             m_highestRxAck);
       
  1283   // Calculate remaining data for COE check
       
  1284   uint32_t remainingData = m_pendingData->SizeFromSeq (
       
  1285       m_firstPendingSequence,
       
  1286       m_nextTxSequence + SequenceNumber(p->GetSize ()));
       
  1287   if (m_closeOnEmpty && remainingData == 0)
       
  1288     { // Add the FIN flag
       
  1289       flags = flags | TcpHeader::FIN;
       
  1290     }
       
  1291 
       
  1292   NS_LOG_LOGIC ("TcpSocketImpl " << this << " retxing seq " << m_highestRxAck);
       
  1293   if (m_retxEvent.IsExpired () )
       
  1294     {
       
  1295       Time rto = m_rtt->RetransmitTimeout ();
       
  1296       NS_LOG_LOGIC ("Schedule retransmission timeout at time "
       
  1297           << Simulator::Now ().GetSeconds () << " to expire at time "
       
  1298           << (Simulator::Now () + rto).GetSeconds ());
       
  1299       m_retxEvent = Simulator::Schedule (rto,&TcpSocketImpl::ReTxTimeout,this);
       
  1300     }
       
  1301   m_rtt->SentSeq (m_highestRxAck,p->GetSize ());
       
  1302   // And send the packet
       
  1303   TcpHeader tcpHeader;
       
  1304   tcpHeader.SetSequenceNumber (m_nextTxSequence);
       
  1305   tcpHeader.SetAckNumber (m_nextRxSequence);
       
  1306   tcpHeader.SetSourcePort (m_endPoint->GetLocalPort());
       
  1307   tcpHeader.SetDestinationPort (m_remotePort);
       
  1308   tcpHeader.SetFlags (flags);
       
  1309   tcpHeader.SetWindowSize (m_advertisedWindowSize);
       
  1310 
       
  1311   m_tcp->SendPacket (p, tcpHeader, m_endPoint->GetLocalAddress (),
       
  1312     m_remoteAddress);
       
  1313 }
       
  1314 
       
  1315 void
       
  1316 TcpSocketImpl::SetSndBufSize (uint32_t size)
       
  1317 {
       
  1318   m_sndBufSize = size;
       
  1319 }
       
  1320 
       
  1321 uint32_t
       
  1322 TcpSocketImpl::GetSndBufSize (void) const
       
  1323 {
       
  1324   return m_sndBufSize;
       
  1325 }
       
  1326 
       
  1327 void
       
  1328 TcpSocketImpl::SetRcvBufSize (uint32_t size)
       
  1329 {
       
  1330   m_rcvBufSize = size;
       
  1331 }
       
  1332 
       
  1333 uint32_t
       
  1334 TcpSocketImpl::GetRcvBufSize (void) const
       
  1335 {
       
  1336   return m_rcvBufSize;
       
  1337 }
       
  1338 
       
  1339 void
       
  1340 TcpSocketImpl::SetSegSize (uint32_t size)
       
  1341 {
       
  1342   m_segmentSize = size;
       
  1343 }
       
  1344 
       
  1345 uint32_t
       
  1346 TcpSocketImpl::GetSegSize (void) const
       
  1347 {
       
  1348   return m_segmentSize;
       
  1349 }
       
  1350 
       
  1351 void
       
  1352 TcpSocketImpl::SetAdvWin (uint32_t window)
       
  1353 {
       
  1354   m_advertisedWindowSize = window;
       
  1355 }
       
  1356 
       
  1357 uint32_t
       
  1358 TcpSocketImpl::GetAdvWin (void) const
       
  1359 {
       
  1360   return m_advertisedWindowSize;
       
  1361 }
       
  1362 
       
  1363 void
       
  1364 TcpSocketImpl::SetSSThresh (uint32_t threshold)
       
  1365 {
       
  1366   m_ssThresh = threshold;
       
  1367 }
       
  1368 
       
  1369 uint32_t
       
  1370 TcpSocketImpl::GetSSThresh (void) const
       
  1371 {
       
  1372   return m_ssThresh;
       
  1373 }
       
  1374 
       
  1375 void
       
  1376 TcpSocketImpl::SetInitialCwnd (uint32_t cwnd)
       
  1377 {
       
  1378   m_initialCWnd = cwnd;
       
  1379 }
       
  1380 
       
  1381 uint32_t
       
  1382 TcpSocketImpl::GetInitialCwnd (void) const
       
  1383 {
       
  1384   return m_initialCWnd;
       
  1385 }
       
  1386 
       
  1387 void 
       
  1388 TcpSocketImpl::SetConnTimeout (Time timeout)
       
  1389 {
       
  1390   m_cnTimeout = timeout;
       
  1391 }
       
  1392 
       
  1393 Time
       
  1394 TcpSocketImpl::GetConnTimeout (void) const
       
  1395 {
       
  1396   return m_cnTimeout;
       
  1397 }
       
  1398 
       
  1399 void 
       
  1400 TcpSocketImpl::SetConnCount (uint32_t count)
       
  1401 {
       
  1402   m_cnCount = count;
       
  1403 }
       
  1404 
       
  1405 uint32_t 
       
  1406 TcpSocketImpl::GetConnCount (void) const
       
  1407 {
       
  1408   return m_cnCount;
       
  1409 }
       
  1410 
       
  1411 void 
       
  1412 TcpSocketImpl::SetDelAckTimeout (Time timeout)
       
  1413 {
       
  1414   m_delAckTimeout = timeout;
       
  1415 }
       
  1416 
       
  1417 Time
       
  1418 TcpSocketImpl::GetDelAckTimeout (void) const
       
  1419 {
       
  1420   return m_delAckTimeout;
       
  1421 }
       
  1422 
       
  1423 void
       
  1424 TcpSocketImpl::SetDelAckMaxCount (uint32_t count)
       
  1425 {
       
  1426   m_delAckMaxCount = count;
       
  1427 }
       
  1428 
       
  1429 uint32_t
       
  1430 TcpSocketImpl::GetDelAckMaxCount (void) const
       
  1431 {
       
  1432   return m_delAckMaxCount;
       
  1433 }
       
  1434 
       
  1435 }//namespace ns3