PageRenderTime 35ms CodeModel.GetById 28ms RepoModel.GetById 2ms app.codeStats 1ms

/src/internet/model/tcp-socket-base.cc

https://bitbucket.org/cttc-lena/ns-3-lena-dev
C++ | 2447 lines | 2019 code | 179 blank | 249 comment | 521 complexity | c57eda109af9d257f75eee39d0713191 MD5 | raw file
Possible License(s): GPL-2.0
  1. /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
  2. /*
  3. * Copyright (c) 2007 Georgia Tech Research Corporation
  4. * Copyright (c) 2010 Adrian Sai-wah Tam
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License version 2 as
  8. * published by the Free Software Foundation;
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program; if not, write to the Free Software
  17. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  18. *
  19. * Author: Adrian Sai-wah Tam <adrian.sw.tam@gmail.com>
  20. */
  21. #define NS_LOG_APPEND_CONTEXT \
  22. if (m_node) { std::clog << Simulator::Now ().GetSeconds () << " [node " << m_node->GetId () << "] "; }
  23. #include "ns3/abort.h"
  24. #include "ns3/node.h"
  25. #include "ns3/inet-socket-address.h"
  26. #include "ns3/inet6-socket-address.h"
  27. #include "ns3/log.h"
  28. #include "ns3/ipv4.h"
  29. #include "ns3/ipv6.h"
  30. #include "ns3/ipv4-interface-address.h"
  31. #include "ns3/ipv4-route.h"
  32. #include "ns3/ipv6-route.h"
  33. #include "ns3/ipv4-routing-protocol.h"
  34. #include "ns3/ipv6-routing-protocol.h"
  35. #include "ns3/simulation-singleton.h"
  36. #include "ns3/simulator.h"
  37. #include "ns3/packet.h"
  38. #include "ns3/uinteger.h"
  39. #include "ns3/double.h"
  40. #include "ns3/trace-source-accessor.h"
  41. #include "tcp-socket-base.h"
  42. #include "tcp-l4-protocol.h"
  43. #include "ipv4-end-point.h"
  44. #include "ipv6-end-point.h"
  45. #include "ipv6-l3-protocol.h"
  46. #include "tcp-header.h"
  47. #include "rtt-estimator.h"
  48. #include <algorithm>
  49. NS_LOG_COMPONENT_DEFINE ("TcpSocketBase");
  50. namespace ns3 {
  51. NS_OBJECT_ENSURE_REGISTERED (TcpSocketBase);
  52. TypeId
  53. TcpSocketBase::GetTypeId (void)
  54. {
  55. static TypeId tid = TypeId ("ns3::TcpSocketBase")
  56. .SetParent<TcpSocket> ()
  57. // .AddAttribute ("TcpState", "State in TCP state machine",
  58. // TypeId::ATTR_GET,
  59. // EnumValue (CLOSED),
  60. // MakeEnumAccessor (&TcpSocketBase::m_state),
  61. // MakeEnumChecker (CLOSED, "Closed"))
  62. .AddAttribute ("MaxSegLifetime",
  63. "Maximum segment lifetime in seconds, use for TIME_WAIT state transition to CLOSED state",
  64. DoubleValue (120), /* RFC793 says MSL=2 minutes*/
  65. MakeDoubleAccessor (&TcpSocketBase::m_msl),
  66. MakeDoubleChecker<double> (0))
  67. .AddAttribute ("MaxWindowSize", "Max size of advertised window",
  68. UintegerValue (65535),
  69. MakeUintegerAccessor (&TcpSocketBase::m_maxWinSize),
  70. MakeUintegerChecker<uint16_t> ())
  71. .AddAttribute ("IcmpCallback", "Callback invoked whenever an icmp error is received on this socket.",
  72. CallbackValue (),
  73. MakeCallbackAccessor (&TcpSocketBase::m_icmpCallback),
  74. MakeCallbackChecker ())
  75. .AddAttribute ("IcmpCallback6", "Callback invoked whenever an icmpv6 error is received on this socket.",
  76. CallbackValue (),
  77. MakeCallbackAccessor (&TcpSocketBase::m_icmpCallback6),
  78. MakeCallbackChecker ())
  79. .AddTraceSource ("RTO",
  80. "Retransmission timeout",
  81. MakeTraceSourceAccessor (&TcpSocketBase::m_rto))
  82. .AddTraceSource ("RTT",
  83. "Last RTT sample",
  84. MakeTraceSourceAccessor (&TcpSocketBase::m_lastRtt))
  85. .AddTraceSource ("NextTxSequence",
  86. "Next sequence number to send (SND.NXT)",
  87. MakeTraceSourceAccessor (&TcpSocketBase::m_nextTxSequence))
  88. .AddTraceSource ("HighestSequence",
  89. "Highest sequence number ever sent in socket's life time",
  90. MakeTraceSourceAccessor (&TcpSocketBase::m_highTxMark))
  91. .AddTraceSource ("State",
  92. "TCP state",
  93. MakeTraceSourceAccessor (&TcpSocketBase::m_state))
  94. .AddTraceSource ("RWND",
  95. "Remote side's flow control window",
  96. MakeTraceSourceAccessor (&TcpSocketBase::m_rWnd))
  97. ;
  98. return tid;
  99. }
  100. TcpSocketBase::TcpSocketBase (void)
  101. : m_dupAckCount (0),
  102. m_delAckCount (0),
  103. m_endPoint (0),
  104. m_endPoint6 (0),
  105. m_node (0),
  106. m_tcp (0),
  107. m_rtt (0),
  108. m_nextTxSequence (0),
  109. // Change this for non-zero initial sequence number
  110. m_highTxMark (0),
  111. m_rxBuffer (0),
  112. m_txBuffer (0),
  113. m_state (CLOSED),
  114. m_errno (ERROR_NOTERROR),
  115. m_closeNotified (false),
  116. m_closeOnEmpty (false),
  117. m_shutdownSend (false),
  118. m_shutdownRecv (false),
  119. m_connected (false),
  120. m_segmentSize (0),
  121. // For attribute initialization consistency (quiet valgrind)
  122. m_rWnd (0)
  123. {
  124. NS_LOG_FUNCTION (this);
  125. }
  126. TcpSocketBase::TcpSocketBase (const TcpSocketBase& sock)
  127. : TcpSocket (sock),
  128. //copy object::m_tid and socket::callbacks
  129. m_dupAckCount (sock.m_dupAckCount),
  130. m_delAckCount (0),
  131. m_delAckMaxCount (sock.m_delAckMaxCount),
  132. m_noDelay (sock.m_noDelay),
  133. m_cnRetries (sock.m_cnRetries),
  134. m_delAckTimeout (sock.m_delAckTimeout),
  135. m_persistTimeout (sock.m_persistTimeout),
  136. m_cnTimeout (sock.m_cnTimeout),
  137. m_endPoint (0),
  138. m_endPoint6 (0),
  139. m_node (sock.m_node),
  140. m_tcp (sock.m_tcp),
  141. m_rtt (0),
  142. m_nextTxSequence (sock.m_nextTxSequence),
  143. m_highTxMark (sock.m_highTxMark),
  144. m_rxBuffer (sock.m_rxBuffer),
  145. m_txBuffer (sock.m_txBuffer),
  146. m_state (sock.m_state),
  147. m_errno (sock.m_errno),
  148. m_closeNotified (sock.m_closeNotified),
  149. m_closeOnEmpty (sock.m_closeOnEmpty),
  150. m_shutdownSend (sock.m_shutdownSend),
  151. m_shutdownRecv (sock.m_shutdownRecv),
  152. m_connected (sock.m_connected),
  153. m_msl (sock.m_msl),
  154. m_segmentSize (sock.m_segmentSize),
  155. m_maxWinSize (sock.m_maxWinSize),
  156. m_rWnd (sock.m_rWnd)
  157. {
  158. NS_LOG_FUNCTION (this);
  159. NS_LOG_LOGIC ("Invoked the copy constructor");
  160. // Copy the rtt estimator if it is set
  161. if (sock.m_rtt)
  162. {
  163. m_rtt = sock.m_rtt->Copy ();
  164. }
  165. // Reset all callbacks to null
  166. Callback<void, Ptr< Socket > > vPS = MakeNullCallback<void, Ptr<Socket> > ();
  167. Callback<void, Ptr<Socket>, const Address &> vPSA = MakeNullCallback<void, Ptr<Socket>, const Address &> ();
  168. Callback<void, Ptr<Socket>, uint32_t> vPSUI = MakeNullCallback<void, Ptr<Socket>, uint32_t> ();
  169. SetConnectCallback (vPS, vPS);
  170. SetDataSentCallback (vPSUI);
  171. SetSendCallback (vPSUI);
  172. SetRecvCallback (vPS);
  173. }
  174. TcpSocketBase::~TcpSocketBase (void)
  175. {
  176. NS_LOG_FUNCTION (this);
  177. m_node = 0;
  178. if (m_endPoint != 0)
  179. {
  180. NS_ASSERT (m_tcp != 0);
  181. /*
  182. * Upon Bind, an Ipv4Endpoint is allocated and set to m_endPoint, and
  183. * DestroyCallback is set to TcpSocketBase::Destroy. If we called
  184. * m_tcp->DeAllocate, it wil destroy its Ipv4EndpointDemux::DeAllocate,
  185. * which in turn destroys my m_endPoint, and in turn invokes
  186. * TcpSocketBase::Destroy to nullify m_node, m_endPoint, and m_tcp.
  187. */
  188. NS_ASSERT (m_endPoint != 0);
  189. m_tcp->DeAllocate (m_endPoint);
  190. NS_ASSERT (m_endPoint == 0);
  191. }
  192. if (m_endPoint6 != 0)
  193. {
  194. NS_ASSERT (m_tcp != 0);
  195. NS_ASSERT (m_endPoint6 != 0);
  196. m_tcp->DeAllocate (m_endPoint6);
  197. NS_ASSERT (m_endPoint6 == 0);
  198. }
  199. m_tcp = 0;
  200. CancelAllTimers ();
  201. }
  202. /* Associate a node with this TCP socket */
  203. void
  204. TcpSocketBase::SetNode (Ptr<Node> node)
  205. {
  206. m_node = node;
  207. }
  208. /* Associate the L4 protocol (e.g. mux/demux) with this socket */
  209. void
  210. TcpSocketBase::SetTcp (Ptr<TcpL4Protocol> tcp)
  211. {
  212. m_tcp = tcp;
  213. }
  214. /* Set an RTT estimator with this socket */
  215. void
  216. TcpSocketBase::SetRtt (Ptr<RttEstimator> rtt)
  217. {
  218. m_rtt = rtt;
  219. }
  220. /* Inherit from Socket class: Returns error code */
  221. enum Socket::SocketErrno
  222. TcpSocketBase::GetErrno (void) const
  223. {
  224. return m_errno;
  225. }
  226. /* Inherit from Socket class: Returns socket type, NS3_SOCK_STREAM */
  227. enum Socket::SocketType
  228. TcpSocketBase::GetSocketType (void) const
  229. {
  230. return NS3_SOCK_STREAM;
  231. }
  232. /* Inherit from Socket class: Returns associated node */
  233. Ptr<Node>
  234. TcpSocketBase::GetNode (void) const
  235. {
  236. NS_LOG_FUNCTION_NOARGS ();
  237. return m_node;
  238. }
  239. /* Inherit from Socket class: Bind socket to an end-point in TcpL4Protocol */
  240. int
  241. TcpSocketBase::Bind (void)
  242. {
  243. NS_LOG_FUNCTION (this);
  244. m_endPoint = m_tcp->Allocate ();
  245. if (0 == m_endPoint)
  246. {
  247. m_errno = ERROR_ADDRNOTAVAIL;
  248. return -1;
  249. }
  250. if (std::find(m_tcp->m_sockets.begin(), m_tcp->m_sockets.end(), this) == m_tcp->m_sockets.end())
  251. {
  252. m_tcp->m_sockets.push_back (this);
  253. }
  254. return SetupCallback ();
  255. }
  256. int
  257. TcpSocketBase::Bind6 (void)
  258. {
  259. NS_LOG_FUNCTION (this);
  260. m_endPoint6 = m_tcp->Allocate6 ();
  261. if (0 == m_endPoint6)
  262. {
  263. m_errno = ERROR_ADDRNOTAVAIL;
  264. return -1;
  265. }
  266. if (std::find(m_tcp->m_sockets.begin(), m_tcp->m_sockets.end(), this) == m_tcp->m_sockets.end())
  267. {
  268. m_tcp->m_sockets.push_back (this);
  269. }
  270. return SetupCallback ();
  271. }
  272. /* Inherit from Socket class: Bind socket (with specific address) to an end-point in TcpL4Protocol */
  273. int
  274. TcpSocketBase::Bind (const Address &address)
  275. {
  276. NS_LOG_FUNCTION (this << address);
  277. if (InetSocketAddress::IsMatchingType (address))
  278. {
  279. InetSocketAddress transport = InetSocketAddress::ConvertFrom (address);
  280. Ipv4Address ipv4 = transport.GetIpv4 ();
  281. uint16_t port = transport.GetPort ();
  282. if (ipv4 == Ipv4Address::GetAny () && port == 0)
  283. {
  284. m_endPoint = m_tcp->Allocate ();
  285. }
  286. else if (ipv4 == Ipv4Address::GetAny () && port != 0)
  287. {
  288. m_endPoint = m_tcp->Allocate (port);
  289. }
  290. else if (ipv4 != Ipv4Address::GetAny () && port == 0)
  291. {
  292. m_endPoint = m_tcp->Allocate (ipv4);
  293. }
  294. else if (ipv4 != Ipv4Address::GetAny () && port != 0)
  295. {
  296. m_endPoint = m_tcp->Allocate (ipv4, port);
  297. }
  298. if (0 == m_endPoint)
  299. {
  300. m_errno = port ? ERROR_ADDRINUSE : ERROR_ADDRNOTAVAIL;
  301. return -1;
  302. }
  303. }
  304. else if (Inet6SocketAddress::IsMatchingType (address))
  305. {
  306. Inet6SocketAddress transport = Inet6SocketAddress::ConvertFrom (address);
  307. Ipv6Address ipv6 = transport.GetIpv6 ();
  308. uint16_t port = transport.GetPort ();
  309. if (ipv6 == Ipv6Address::GetAny () && port == 0)
  310. {
  311. m_endPoint6 = m_tcp->Allocate6 ();
  312. }
  313. else if (ipv6 == Ipv6Address::GetAny () && port != 0)
  314. {
  315. m_endPoint6 = m_tcp->Allocate6 (port);
  316. }
  317. else if (ipv6 != Ipv6Address::GetAny () && port == 0)
  318. {
  319. m_endPoint6 = m_tcp->Allocate6 (ipv6);
  320. }
  321. else if (ipv6 != Ipv6Address::GetAny () && port != 0)
  322. {
  323. m_endPoint6 = m_tcp->Allocate6 (ipv6, port);
  324. }
  325. if (0 == m_endPoint6)
  326. {
  327. m_errno = port ? ERROR_ADDRINUSE : ERROR_ADDRNOTAVAIL;
  328. return -1;
  329. }
  330. }
  331. else
  332. {
  333. m_errno = ERROR_INVAL;
  334. return -1;
  335. }
  336. if (std::find(m_tcp->m_sockets.begin(), m_tcp->m_sockets.end(), this) == m_tcp->m_sockets.end())
  337. {
  338. m_tcp->m_sockets.push_back (this);
  339. }
  340. NS_LOG_LOGIC ("TcpSocketBase " << this << " got an endpoint: " << m_endPoint);
  341. return SetupCallback ();
  342. }
  343. /* Inherit from Socket class: Initiate connection to a remote address:port */
  344. int
  345. TcpSocketBase::Connect (const Address & address)
  346. {
  347. NS_LOG_FUNCTION (this << address);
  348. // If haven't do so, Bind() this socket first
  349. if (InetSocketAddress::IsMatchingType (address) && m_endPoint6 == 0)
  350. {
  351. if (m_endPoint == 0)
  352. {
  353. if (Bind () == -1)
  354. {
  355. NS_ASSERT (m_endPoint == 0);
  356. return -1; // Bind() failed
  357. }
  358. NS_ASSERT (m_endPoint != 0);
  359. }
  360. InetSocketAddress transport = InetSocketAddress::ConvertFrom (address);
  361. m_endPoint->SetPeer (transport.GetIpv4 (), transport.GetPort ());
  362. m_endPoint6 = 0;
  363. // Get the appropriate local address and port number from the routing protocol and set up endpoint
  364. if (SetupEndpoint () != 0)
  365. { // Route to destination does not exist
  366. return -1;
  367. }
  368. }
  369. else if (Inet6SocketAddress::IsMatchingType (address) && m_endPoint == 0)
  370. {
  371. // If we are operating on a v4-mapped address, translate the address to
  372. // a v4 address and re-call this function
  373. Inet6SocketAddress transport = Inet6SocketAddress::ConvertFrom (address);
  374. Ipv6Address v6Addr = transport.GetIpv6 ();
  375. if (v6Addr.IsIpv4MappedAddress () == true)
  376. {
  377. Ipv4Address v4Addr = v6Addr.GetIpv4MappedAddress ();
  378. return Connect (InetSocketAddress (v4Addr, transport.GetPort ()));
  379. }
  380. if (m_endPoint6 == 0)
  381. {
  382. if (Bind6 () == -1)
  383. {
  384. NS_ASSERT (m_endPoint6 == 0);
  385. return -1; // Bind() failed
  386. }
  387. NS_ASSERT (m_endPoint6 != 0);
  388. }
  389. m_endPoint6->SetPeer (v6Addr, transport.GetPort ());
  390. m_endPoint = 0;
  391. // Get the appropriate local address and port number from the routing protocol and set up endpoint
  392. if (SetupEndpoint6 () != 0)
  393. { // Route to destination does not exist
  394. return -1;
  395. }
  396. }
  397. else
  398. {
  399. m_errno = ERROR_INVAL;
  400. return -1;
  401. }
  402. // Re-initialize parameters in case this socket is being reused after CLOSE
  403. m_rtt->Reset ();
  404. m_cnCount = m_cnRetries;
  405. // DoConnect() will do state-checking and send a SYN packet
  406. return DoConnect ();
  407. }
  408. /* Inherit from Socket class: Listen on the endpoint for an incoming connection */
  409. int
  410. TcpSocketBase::Listen (void)
  411. {
  412. NS_LOG_FUNCTION (this);
  413. // Linux quits EINVAL if we're not in CLOSED state, so match what they do
  414. if (m_state != CLOSED)
  415. {
  416. m_errno = ERROR_INVAL;
  417. return -1;
  418. }
  419. // In other cases, set the state to LISTEN and done
  420. NS_LOG_INFO ("CLOSED -> LISTEN");
  421. m_state = LISTEN;
  422. return 0;
  423. }
  424. /* Inherit from Socket class: Kill this socket and signal the peer (if any) */
  425. int
  426. TcpSocketBase::Close (void)
  427. {
  428. NS_LOG_FUNCTION (this);
  429. /// \internal
  430. /// First we check to see if there is any unread rx data.
  431. /// \bugid{426} claims we should send reset in this case.
  432. if (m_rxBuffer.Size () != 0)
  433. {
  434. NS_LOG_INFO ("Socket " << this << " << unread rx data during close. Sending reset");
  435. SendRST ();
  436. return 0;
  437. }
  438. if (m_txBuffer.SizeFromSequence (m_nextTxSequence) > 0)
  439. { // App close with pending data must wait until all data transmitted
  440. if (m_closeOnEmpty == false)
  441. {
  442. m_closeOnEmpty = true;
  443. NS_LOG_INFO ("Socket " << this << " deferring close, state " << TcpStateName[m_state]);
  444. }
  445. return 0;
  446. }
  447. return DoClose ();
  448. }
  449. /* Inherit from Socket class: Signal a termination of send */
  450. int
  451. TcpSocketBase::ShutdownSend (void)
  452. {
  453. NS_LOG_FUNCTION (this);
  454. //this prevents data from being added to the buffer
  455. m_shutdownSend = true;
  456. m_closeOnEmpty = true;
  457. //if buffer is already empty, send a fin now
  458. //otherwise fin will go when buffer empties.
  459. if (m_txBuffer.Size () == 0)
  460. {
  461. if (m_state == ESTABLISHED || m_state == CLOSE_WAIT)
  462. {
  463. NS_LOG_INFO("Emtpy tx buffer, send fin");
  464. SendEmptyPacket (TcpHeader::FIN);
  465. if (m_state == ESTABLISHED)
  466. { // On active close: I am the first one to send FIN
  467. NS_LOG_INFO ("ESTABLISHED -> FIN_WAIT_1");
  468. m_state = FIN_WAIT_1;
  469. }
  470. else
  471. { // On passive close: Peer sent me FIN already
  472. NS_LOG_INFO ("CLOSE_WAIT -> LAST_ACK");
  473. m_state = LAST_ACK;
  474. }
  475. }
  476. }
  477. return 0;
  478. }
  479. /* Inherit from Socket class: Signal a termination of receive */
  480. int
  481. TcpSocketBase::ShutdownRecv (void)
  482. {
  483. NS_LOG_FUNCTION (this);
  484. m_shutdownRecv = true;
  485. return 0;
  486. }
  487. /* Inherit from Socket class: Send a packet. Parameter flags is not used.
  488. Packet has no TCP header. Invoked by upper-layer application */
  489. int
  490. TcpSocketBase::Send (Ptr<Packet> p, uint32_t flags)
  491. {
  492. NS_LOG_FUNCTION (this << p);
  493. NS_ABORT_MSG_IF (flags, "use of flags is not supported in TcpSocketBase::Send()");
  494. if (m_state == ESTABLISHED || m_state == SYN_SENT || m_state == CLOSE_WAIT)
  495. {
  496. // Store the packet into Tx buffer
  497. if (!m_txBuffer.Add (p))
  498. { // TxBuffer overflow, send failed
  499. m_errno = ERROR_MSGSIZE;
  500. return -1;
  501. }
  502. if (m_shutdownSend)
  503. {
  504. m_errno = ERROR_SHUTDOWN;
  505. return -1;
  506. }
  507. // Submit the data to lower layers
  508. NS_LOG_LOGIC ("txBufSize=" << m_txBuffer.Size () << " state " << TcpStateName[m_state]);
  509. if (m_state == ESTABLISHED || m_state == CLOSE_WAIT)
  510. { // Try to send the data out
  511. SendPendingData (m_connected);
  512. }
  513. return p->GetSize ();
  514. }
  515. else
  516. { // Connection not established yet
  517. m_errno = ERROR_NOTCONN;
  518. return -1; // Send failure
  519. }
  520. }
  521. /* Inherit from Socket class: In TcpSocketBase, it is same as Send() call */
  522. int
  523. TcpSocketBase::SendTo (Ptr<Packet> p, uint32_t flags, const Address &address)
  524. {
  525. return Send (p, flags); // SendTo() and Send() are the same
  526. }
  527. /* Inherit from Socket class: Return data to upper-layer application. Parameter flags
  528. is not used. Data is returned as a packet of size no larger than maxSize */
  529. Ptr<Packet>
  530. TcpSocketBase::Recv (uint32_t maxSize, uint32_t flags)
  531. {
  532. NS_LOG_FUNCTION (this);
  533. NS_ABORT_MSG_IF (flags, "use of flags is not supported in TcpSocketBase::Recv()");
  534. if (m_rxBuffer.Size () == 0 && m_state == CLOSE_WAIT)
  535. {
  536. return Create<Packet> (); // Send EOF on connection close
  537. }
  538. Ptr<Packet> outPacket = m_rxBuffer.Extract (maxSize);
  539. if (outPacket != 0 && outPacket->GetSize () != 0)
  540. {
  541. SocketAddressTag tag;
  542. if (m_endPoint != 0)
  543. {
  544. tag.SetAddress (InetSocketAddress (m_endPoint->GetPeerAddress (), m_endPoint->GetPeerPort ()));
  545. }
  546. else if (m_endPoint6 != 0)
  547. {
  548. tag.SetAddress (Inet6SocketAddress (m_endPoint6->GetPeerAddress (), m_endPoint6->GetPeerPort ()));
  549. }
  550. outPacket->AddPacketTag (tag);
  551. }
  552. return outPacket;
  553. }
  554. /* Inherit from Socket class: Recv and return the remote's address */
  555. Ptr<Packet>
  556. TcpSocketBase::RecvFrom (uint32_t maxSize, uint32_t flags, Address &fromAddress)
  557. {
  558. NS_LOG_FUNCTION (this << maxSize << flags);
  559. Ptr<Packet> packet = Recv (maxSize, flags);
  560. // Null packet means no data to read, and an empty packet indicates EOF
  561. if (packet != 0 && packet->GetSize () != 0)
  562. {
  563. if (m_endPoint != 0)
  564. {
  565. fromAddress = InetSocketAddress (m_endPoint->GetPeerAddress (), m_endPoint->GetPeerPort ());
  566. }
  567. else if (m_endPoint6 != 0)
  568. {
  569. fromAddress = Inet6SocketAddress (m_endPoint6->GetPeerAddress (), m_endPoint6->GetPeerPort ());
  570. }
  571. else
  572. {
  573. fromAddress = InetSocketAddress (Ipv4Address::GetZero (), 0);
  574. }
  575. }
  576. return packet;
  577. }
  578. /* Inherit from Socket class: Get the max number of bytes an app can send */
  579. uint32_t
  580. TcpSocketBase::GetTxAvailable (void) const
  581. {
  582. NS_LOG_FUNCTION (this);
  583. return m_txBuffer.Available ();
  584. }
  585. /* Inherit from Socket class: Get the max number of bytes an app can read */
  586. uint32_t
  587. TcpSocketBase::GetRxAvailable (void) const
  588. {
  589. NS_LOG_FUNCTION (this);
  590. return m_rxBuffer.Available ();
  591. }
  592. /* Inherit from Socket class: Return local address:port */
  593. int
  594. TcpSocketBase::GetSockName (Address &address) const
  595. {
  596. NS_LOG_FUNCTION (this);
  597. if (m_endPoint != 0)
  598. {
  599. address = InetSocketAddress (m_endPoint->GetLocalAddress (), m_endPoint->GetLocalPort ());
  600. }
  601. else if (m_endPoint6 != 0)
  602. {
  603. address = Inet6SocketAddress (m_endPoint6->GetLocalAddress (), m_endPoint6->GetLocalPort ());
  604. }
  605. else
  606. { // It is possible to call this method on a socket without a name
  607. // in which case, behavior is unspecified
  608. // Should this return an InetSocketAddress or an Inet6SocketAddress?
  609. address = InetSocketAddress (Ipv4Address::GetZero (), 0);
  610. }
  611. return 0;
  612. }
  613. /* Inherit from Socket class: Bind this socket to the specified NetDevice */
  614. void
  615. TcpSocketBase::BindToNetDevice (Ptr<NetDevice> netdevice)
  616. {
  617. NS_LOG_FUNCTION (netdevice);
  618. Socket::BindToNetDevice (netdevice); // Includes sanity check
  619. if (m_endPoint == 0 && m_endPoint6 == 0)
  620. {
  621. if (Bind () == -1)
  622. {
  623. NS_ASSERT ((m_endPoint == 0 && m_endPoint6 == 0));
  624. return;
  625. }
  626. NS_ASSERT ((m_endPoint != 0 && m_endPoint6 != 0));
  627. }
  628. if (m_endPoint != 0)
  629. {
  630. m_endPoint->BindToNetDevice (netdevice);
  631. }
  632. // No BindToNetDevice() for Ipv6EndPoint
  633. return;
  634. }
  635. /* Clean up after Bind. Set up callback functions in the end-point. */
  636. int
  637. TcpSocketBase::SetupCallback (void)
  638. {
  639. NS_LOG_FUNCTION (this);
  640. if (m_endPoint == 0 && m_endPoint6 == 0)
  641. {
  642. return -1;
  643. }
  644. if (m_endPoint != 0)
  645. {
  646. m_endPoint->SetRxCallback (MakeCallback (&TcpSocketBase::ForwardUp, Ptr<TcpSocketBase> (this)));
  647. m_endPoint->SetIcmpCallback (MakeCallback (&TcpSocketBase::ForwardIcmp, Ptr<TcpSocketBase> (this)));
  648. m_endPoint->SetDestroyCallback (MakeCallback (&TcpSocketBase::Destroy, Ptr<TcpSocketBase> (this)));
  649. }
  650. if (m_endPoint6 != 0)
  651. {
  652. m_endPoint6->SetRxCallback (MakeCallback (&TcpSocketBase::ForwardUp6, Ptr<TcpSocketBase> (this)));
  653. m_endPoint6->SetIcmpCallback (MakeCallback (&TcpSocketBase::ForwardIcmp6, Ptr<TcpSocketBase> (this)));
  654. m_endPoint6->SetDestroyCallback (MakeCallback (&TcpSocketBase::Destroy6, Ptr<TcpSocketBase> (this)));
  655. }
  656. return 0;
  657. }
  658. /* Perform the real connection tasks: Send SYN if allowed, RST if invalid */
  659. int
  660. TcpSocketBase::DoConnect (void)
  661. {
  662. NS_LOG_FUNCTION (this);
  663. // A new connection is allowed only if this socket does not have a connection
  664. if (m_state == CLOSED || m_state == LISTEN || m_state == SYN_SENT || m_state == LAST_ACK || m_state == CLOSE_WAIT)
  665. { // send a SYN packet and change state into SYN_SENT
  666. SendEmptyPacket (TcpHeader::SYN);
  667. NS_LOG_INFO (TcpStateName[m_state] << " -> SYN_SENT");
  668. m_state = SYN_SENT;
  669. }
  670. else if (m_state != TIME_WAIT)
  671. { // In states SYN_RCVD, ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, and CLOSING, an connection
  672. // exists. We send RST, tear down everything, and close this socket.
  673. SendRST ();
  674. CloseAndNotify ();
  675. }
  676. return 0;
  677. }
  678. /* Do the action to close the socket. Usually send a packet with appropriate
  679. flags depended on the current m_state. */
  680. int
  681. TcpSocketBase::DoClose (void)
  682. {
  683. NS_LOG_FUNCTION (this);
  684. switch (m_state)
  685. {
  686. case SYN_RCVD:
  687. case ESTABLISHED:
  688. // send FIN to close the peer
  689. SendEmptyPacket (TcpHeader::FIN);
  690. NS_LOG_INFO ("ESTABLISHED -> FIN_WAIT_1");
  691. m_state = FIN_WAIT_1;
  692. break;
  693. case CLOSE_WAIT:
  694. // send FIN+ACK to close the peer
  695. SendEmptyPacket (TcpHeader::FIN | TcpHeader::ACK);
  696. NS_LOG_INFO ("CLOSE_WAIT -> LAST_ACK");
  697. m_state = LAST_ACK;
  698. break;
  699. case SYN_SENT:
  700. case CLOSING:
  701. // Send RST if application closes in SYN_SENT and CLOSING
  702. SendRST ();
  703. CloseAndNotify ();
  704. break;
  705. case LISTEN:
  706. case LAST_ACK:
  707. // In these three states, move to CLOSED and tear down the end point
  708. CloseAndNotify ();
  709. break;
  710. case CLOSED:
  711. case FIN_WAIT_1:
  712. case FIN_WAIT_2:
  713. case TIME_WAIT:
  714. default: /* mute compiler */
  715. // Do nothing in these four states
  716. break;
  717. }
  718. return 0;
  719. }
  720. /* Peacefully close the socket by notifying the upper layer and deallocate end point */
  721. void
  722. TcpSocketBase::CloseAndNotify (void)
  723. {
  724. NS_LOG_FUNCTION (this);
  725. if (!m_closeNotified)
  726. {
  727. NotifyNormalClose ();
  728. }
  729. if (m_state != TIME_WAIT)
  730. {
  731. DeallocateEndPoint ();
  732. }
  733. m_closeNotified = true;
  734. NS_LOG_INFO (TcpStateName[m_state] << " -> CLOSED");
  735. CancelAllTimers ();
  736. m_state = CLOSED;
  737. }
  738. /* Tell if a sequence number range is out side the range that my rx buffer can
  739. accpet */
  740. bool
  741. TcpSocketBase::OutOfRange (SequenceNumber32 head, SequenceNumber32 tail) const
  742. {
  743. if (m_state == LISTEN || m_state == SYN_SENT || m_state == SYN_RCVD)
  744. { // Rx buffer in these states are not initialized.
  745. return false;
  746. }
  747. if (m_state == LAST_ACK || m_state == CLOSING || m_state == CLOSE_WAIT)
  748. { // In LAST_ACK and CLOSING states, it only wait for an ACK and the
  749. // sequence number must equals to m_rxBuffer.NextRxSequence ()
  750. return (m_rxBuffer.NextRxSequence () != head);
  751. }
  752. // In all other cases, check if the sequence number is in range
  753. return (tail < m_rxBuffer.NextRxSequence () || m_rxBuffer.MaxRxSequence () <= head);
  754. }
  755. /* Function called by the L3 protocol when it received a packet to pass on to
  756. the TCP. This function is registered as the "RxCallback" function in
  757. SetupCallback(), which invoked by Bind(), and CompleteFork() */
  758. void
  759. TcpSocketBase::ForwardUp (Ptr<Packet> packet, Ipv4Header header, uint16_t port,
  760. Ptr<Ipv4Interface> incomingInterface)
  761. {
  762. DoForwardUp (packet, header, port, incomingInterface);
  763. }
  764. void
  765. TcpSocketBase::ForwardUp6 (Ptr<Packet> packet, Ipv6Header header, uint16_t port, Ptr<Ipv6Interface> incomingInterface)
  766. {
  767. DoForwardUp (packet, header, port);
  768. }
  769. void
  770. TcpSocketBase::ForwardIcmp (Ipv4Address icmpSource, uint8_t icmpTtl,
  771. uint8_t icmpType, uint8_t icmpCode,
  772. uint32_t icmpInfo)
  773. {
  774. NS_LOG_FUNCTION (this << icmpSource << (uint32_t)icmpTtl << (uint32_t)icmpType <<
  775. (uint32_t)icmpCode << icmpInfo);
  776. if (!m_icmpCallback.IsNull ())
  777. {
  778. m_icmpCallback (icmpSource, icmpTtl, icmpType, icmpCode, icmpInfo);
  779. }
  780. }
  781. void
  782. TcpSocketBase::ForwardIcmp6 (Ipv6Address icmpSource, uint8_t icmpTtl,
  783. uint8_t icmpType, uint8_t icmpCode,
  784. uint32_t icmpInfo)
  785. {
  786. NS_LOG_FUNCTION (this << icmpSource << (uint32_t)icmpTtl << (uint32_t)icmpType <<
  787. (uint32_t)icmpCode << icmpInfo);
  788. if (!m_icmpCallback6.IsNull ())
  789. {
  790. m_icmpCallback6 (icmpSource, icmpTtl, icmpType, icmpCode, icmpInfo);
  791. }
  792. }
  793. /* The real function to handle the incoming packet from lower layers. This is
  794. wrapped by ForwardUp() so that this function can be overloaded by daughter
  795. classes. */
  796. void
  797. TcpSocketBase::DoForwardUp (Ptr<Packet> packet, Ipv4Header header, uint16_t port,
  798. Ptr<Ipv4Interface> incomingInterface)
  799. {
  800. NS_LOG_LOGIC ("Socket " << this << " forward up " <<
  801. m_endPoint->GetPeerAddress () <<
  802. ":" << m_endPoint->GetPeerPort () <<
  803. " to " << m_endPoint->GetLocalAddress () <<
  804. ":" << m_endPoint->GetLocalPort ());
  805. Address fromAddress = InetSocketAddress (header.GetSource (), port);
  806. Address toAddress = InetSocketAddress (header.GetDestination (), m_endPoint->GetLocalPort ());
  807. // Peel off TCP header and do validity checking
  808. TcpHeader tcpHeader;
  809. packet->RemoveHeader (tcpHeader);
  810. if (tcpHeader.GetFlags () & TcpHeader::ACK)
  811. {
  812. EstimateRtt (tcpHeader);
  813. }
  814. ReadOptions (tcpHeader);
  815. // Update Rx window size, i.e. the flow control window
  816. if (m_rWnd.Get () == 0 && tcpHeader.GetWindowSize () != 0)
  817. { // persist probes end
  818. NS_LOG_LOGIC (this << " Leaving zerowindow persist state");
  819. m_persistEvent.Cancel ();
  820. }
  821. m_rWnd = tcpHeader.GetWindowSize ();
  822. // Discard fully out of range data packets
  823. if (packet->GetSize ()
  824. && OutOfRange (tcpHeader.GetSequenceNumber (), tcpHeader.GetSequenceNumber () + packet->GetSize ()))
  825. {
  826. NS_LOG_LOGIC ("At state " << TcpStateName[m_state] <<
  827. " received packet of seq [" << tcpHeader.GetSequenceNumber () <<
  828. ":" << tcpHeader.GetSequenceNumber () + packet->GetSize () <<
  829. ") out of range [" << m_rxBuffer.NextRxSequence () << ":" <<
  830. m_rxBuffer.MaxRxSequence () << ")");
  831. // Acknowledgement should be sent for all unacceptable packets (RFC793, p.69)
  832. if (m_state == ESTABLISHED && !(tcpHeader.GetFlags () & TcpHeader::RST))
  833. {
  834. SendEmptyPacket (TcpHeader::ACK);
  835. }
  836. return;
  837. }
  838. // TCP state machine code in different process functions
  839. // C.f.: tcp_rcv_state_process() in tcp_input.c in Linux kernel
  840. switch (m_state)
  841. {
  842. case ESTABLISHED:
  843. ProcessEstablished (packet, tcpHeader);
  844. break;
  845. case LISTEN:
  846. ProcessListen (packet, tcpHeader, fromAddress, toAddress);
  847. break;
  848. case TIME_WAIT:
  849. // Do nothing
  850. break;
  851. case CLOSED:
  852. // Send RST if the incoming packet is not a RST
  853. if ((tcpHeader.GetFlags () & ~(TcpHeader::PSH | TcpHeader::URG)) != TcpHeader::RST)
  854. { // Since m_endPoint is not configured yet, we cannot use SendRST here
  855. TcpHeader h;
  856. h.SetFlags (TcpHeader::RST);
  857. h.SetSequenceNumber (m_nextTxSequence);
  858. h.SetAckNumber (m_rxBuffer.NextRxSequence ());
  859. h.SetSourcePort (tcpHeader.GetDestinationPort ());
  860. h.SetDestinationPort (tcpHeader.GetSourcePort ());
  861. h.SetWindowSize (AdvertisedWindowSize ());
  862. AddOptions (h);
  863. m_tcp->SendPacket (Create<Packet> (), h, header.GetDestination (), header.GetSource (), m_boundnetdevice);
  864. }
  865. break;
  866. case SYN_SENT:
  867. ProcessSynSent (packet, tcpHeader);
  868. break;
  869. case SYN_RCVD:
  870. ProcessSynRcvd (packet, tcpHeader, fromAddress, toAddress);
  871. break;
  872. case FIN_WAIT_1:
  873. case FIN_WAIT_2:
  874. case CLOSE_WAIT:
  875. ProcessWait (packet, tcpHeader);
  876. break;
  877. case CLOSING:
  878. ProcessClosing (packet, tcpHeader);
  879. break;
  880. case LAST_ACK:
  881. ProcessLastAck (packet, tcpHeader);
  882. break;
  883. default: // mute compiler
  884. break;
  885. }
  886. }
  887. void
  888. TcpSocketBase::DoForwardUp (Ptr<Packet> packet, Ipv6Header header, uint16_t port)
  889. {
  890. NS_LOG_LOGIC ("Socket " << this << " forward up " <<
  891. m_endPoint6->GetPeerAddress () <<
  892. ":" << m_endPoint6->GetPeerPort () <<
  893. " to " << m_endPoint6->GetLocalAddress () <<
  894. ":" << m_endPoint6->GetLocalPort ());
  895. Address fromAddress = Inet6SocketAddress (header.GetSourceAddress (), port);
  896. Address toAddress = Inet6SocketAddress (header.GetDestinationAddress (), m_endPoint6->GetLocalPort ());
  897. // Peel off TCP header and do validity checking
  898. TcpHeader tcpHeader;
  899. packet->RemoveHeader (tcpHeader);
  900. if (tcpHeader.GetFlags () & TcpHeader::ACK)
  901. {
  902. EstimateRtt (tcpHeader);
  903. }
  904. ReadOptions (tcpHeader);
  905. // Update Rx window size, i.e. the flow control window
  906. if (m_rWnd.Get () == 0 && tcpHeader.GetWindowSize () != 0)
  907. { // persist probes end
  908. NS_LOG_LOGIC (this << " Leaving zerowindow persist state");
  909. m_persistEvent.Cancel ();
  910. }
  911. m_rWnd = tcpHeader.GetWindowSize ();
  912. // Discard fully out of range packets
  913. if (packet->GetSize ()
  914. && OutOfRange (tcpHeader.GetSequenceNumber (), tcpHeader.GetSequenceNumber () + packet->GetSize ()))
  915. {
  916. NS_LOG_LOGIC ("At state " << TcpStateName[m_state] <<
  917. " received packet of seq [" << tcpHeader.GetSequenceNumber () <<
  918. ":" << tcpHeader.GetSequenceNumber () + packet->GetSize () <<
  919. ") out of range [" << m_rxBuffer.NextRxSequence () << ":" <<
  920. m_rxBuffer.MaxRxSequence () << ")");
  921. // Acknowledgement should be sent for all unacceptable packets (RFC793, p.69)
  922. if (m_state == ESTABLISHED && !(tcpHeader.GetFlags () & TcpHeader::RST))
  923. {
  924. SendEmptyPacket (TcpHeader::ACK);
  925. }
  926. return;
  927. }
  928. // TCP state machine code in different process functions
  929. // C.f.: tcp_rcv_state_process() in tcp_input.c in Linux kernel
  930. switch (m_state)
  931. {
  932. case ESTABLISHED:
  933. ProcessEstablished (packet, tcpHeader);
  934. break;
  935. case LISTEN:
  936. ProcessListen (packet, tcpHeader, fromAddress, toAddress);
  937. break;
  938. case TIME_WAIT:
  939. // Do nothing
  940. break;
  941. case CLOSED:
  942. // Send RST if the incoming packet is not a RST
  943. if ((tcpHeader.GetFlags () & ~(TcpHeader::PSH | TcpHeader::URG)) != TcpHeader::RST)
  944. { // Since m_endPoint is not configured yet, we cannot use SendRST here
  945. TcpHeader h;
  946. h.SetFlags (TcpHeader::RST);
  947. h.SetSequenceNumber (m_nextTxSequence);
  948. h.SetAckNumber (m_rxBuffer.NextRxSequence ());
  949. h.SetSourcePort (tcpHeader.GetDestinationPort ());
  950. h.SetDestinationPort (tcpHeader.GetSourcePort ());
  951. h.SetWindowSize (AdvertisedWindowSize ());
  952. AddOptions (h);
  953. m_tcp->SendPacket (Create<Packet> (), h, header.GetDestinationAddress (), header.GetSourceAddress (), m_boundnetdevice);
  954. }
  955. break;
  956. case SYN_SENT:
  957. ProcessSynSent (packet, tcpHeader);
  958. break;
  959. case SYN_RCVD:
  960. ProcessSynRcvd (packet, tcpHeader, fromAddress, toAddress);
  961. break;
  962. case FIN_WAIT_1:
  963. case FIN_WAIT_2:
  964. case CLOSE_WAIT:
  965. ProcessWait (packet, tcpHeader);
  966. break;
  967. case CLOSING:
  968. ProcessClosing (packet, tcpHeader);
  969. break;
  970. case LAST_ACK:
  971. ProcessLastAck (packet, tcpHeader);
  972. break;
  973. default: // mute compiler
  974. break;
  975. }
  976. }
  977. /* Received a packet upon ESTABLISHED state. This function is mimicking the
  978. role of tcp_rcv_established() in tcp_input.c in Linux kernel. */
  979. void
  980. TcpSocketBase::ProcessEstablished (Ptr<Packet> packet, const TcpHeader& tcpHeader)
  981. {
  982. NS_LOG_FUNCTION (this << tcpHeader);
  983. // Extract the flags. PSH and URG are not honoured.
  984. uint8_t tcpflags = tcpHeader.GetFlags () & ~(TcpHeader::PSH | TcpHeader::URG);
  985. // Different flags are different events
  986. if (tcpflags == TcpHeader::ACK)
  987. {
  988. ReceivedAck (packet, tcpHeader);
  989. }
  990. else if (tcpflags == TcpHeader::SYN)
  991. { // Received SYN, old NS-3 behaviour is to set state to SYN_RCVD and
  992. // respond with a SYN+ACK. But it is not a legal state transition as of
  993. // RFC793. Thus this is ignored.
  994. }
  995. else if (tcpflags == (TcpHeader::SYN | TcpHeader::ACK))
  996. { // No action for received SYN+ACK, it is probably a duplicated packet
  997. }
  998. else if (tcpflags == TcpHeader::FIN || tcpflags == (TcpHeader::FIN | TcpHeader::ACK))
  999. { // Received FIN or FIN+ACK, bring down this socket nicely
  1000. PeerClose (packet, tcpHeader);
  1001. }
  1002. else if (tcpflags == 0)
  1003. { // No flags means there is only data
  1004. ReceivedData (packet, tcpHeader);
  1005. if (m_rxBuffer.Finished ())
  1006. {
  1007. PeerClose (packet, tcpHeader);
  1008. }
  1009. }
  1010. else
  1011. { // Received RST or the TCP flags is invalid, in either case, terminate this socket
  1012. if (tcpflags != TcpHeader::RST)
  1013. { // this must be an invalid flag, send reset
  1014. NS_LOG_LOGIC ("Illegal flag " << tcpflags << " received. Reset packet is sent.");
  1015. SendRST ();
  1016. }
  1017. CloseAndNotify ();
  1018. }
  1019. }
  1020. /* Process the newly received ACK */
  1021. void
  1022. TcpSocketBase::ReceivedAck (Ptr<Packet> packet, const TcpHeader& tcpHeader)
  1023. {
  1024. NS_LOG_FUNCTION (this << tcpHeader);
  1025. // Received ACK. Compare the ACK number against highest unacked seqno
  1026. if (0 == (tcpHeader.GetFlags () & TcpHeader::ACK))
  1027. { // Ignore if no ACK flag
  1028. }
  1029. else if (tcpHeader.GetAckNumber () < m_txBuffer.HeadSequence ())
  1030. { // Case 1: Old ACK, ignored.
  1031. NS_LOG_LOGIC ("Ignored ack of " << tcpHeader.GetAckNumber ());
  1032. }
  1033. else if (tcpHeader.GetAckNumber () == m_txBuffer.HeadSequence ())
  1034. { // Case 2: Potentially a duplicated ACK
  1035. if (tcpHeader.GetAckNumber () < m_nextTxSequence && packet->GetSize() == 0)
  1036. {
  1037. NS_LOG_LOGIC ("Dupack of " << tcpHeader.GetAckNumber ());
  1038. DupAck (tcpHeader, ++m_dupAckCount);
  1039. }
  1040. // otherwise, the ACK is precisely equal to the nextTxSequence
  1041. NS_ASSERT (tcpHeader.GetAckNumber () <= m_nextTxSequence);
  1042. }
  1043. else if (tcpHeader.GetAckNumber () > m_txBuffer.HeadSequence ())
  1044. { // Case 3: New ACK, reset m_dupAckCount and update m_txBuffer
  1045. NS_LOG_LOGIC ("New ack of " << tcpHeader.GetAckNumber ());
  1046. NewAck (tcpHeader.GetAckNumber ());
  1047. m_dupAckCount = 0;
  1048. }
  1049. // If there is any data piggybacked, store it into m_rxBuffer
  1050. if (packet->GetSize () > 0)
  1051. {
  1052. ReceivedData (packet, tcpHeader);
  1053. }
  1054. }
  1055. /* Received a packet upon LISTEN state. */
  1056. void
  1057. TcpSocketBase::ProcessListen (Ptr<Packet> packet, const TcpHeader& tcpHeader,
  1058. const Address& fromAddress, const Address& toAddress)
  1059. {
  1060. NS_LOG_FUNCTION (this << tcpHeader);
  1061. // Extract the flags. PSH and URG are not honoured.
  1062. uint8_t tcpflags = tcpHeader.GetFlags () & ~(TcpHeader::PSH | TcpHeader::URG);
  1063. // Fork a socket if received a SYN. Do nothing otherwise.
  1064. // C.f.: the LISTEN part in tcp_v4_do_rcv() in tcp_ipv4.c in Linux kernel
  1065. if (tcpflags != TcpHeader::SYN)
  1066. {
  1067. return;
  1068. }
  1069. // Call socket's notify function to let the server app know we got a SYN
  1070. // If the server app refuses the connection, do nothing
  1071. if (!NotifyConnectionRequest (fromAddress))
  1072. {
  1073. return;
  1074. }
  1075. // Clone the socket, simulate fork
  1076. Ptr<TcpSocketBase> newSock = Fork ();
  1077. NS_LOG_LOGIC ("Cloned a TcpSocketBase " << newSock);
  1078. Simulator::ScheduleNow (&TcpSocketBase::CompleteFork, newSock,
  1079. packet, tcpHeader, fromAddress, toAddress);
  1080. }
  1081. /* Received a packet upon SYN_SENT */
  1082. void
  1083. TcpSocketBase::ProcessSynSent (Ptr<Packet> packet, const TcpHeader& tcpHeader)
  1084. {
  1085. NS_LOG_FUNCTION (this << tcpHeader);
  1086. // Extract the flags. PSH and URG are not honoured.
  1087. uint8_t tcpflags = tcpHeader.GetFlags () & ~(TcpHeader::PSH | TcpHeader::URG);
  1088. if (tcpflags == 0)
  1089. { // Bare data, accept it and move to ESTABLISHED state. This is not a normal behaviour. Remove this?
  1090. NS_LOG_INFO ("SYN_SENT -> ESTABLISHED");
  1091. m_state = ESTABLISHED;
  1092. m_connected = true;
  1093. m_retxEvent.Cancel ();
  1094. m_delAckCount = m_delAckMaxCount;
  1095. ReceivedData (packet, tcpHeader);
  1096. Simulator::ScheduleNow (&TcpSocketBase::ConnectionSucceeded, this);
  1097. }
  1098. else if (tcpflags == TcpHeader::ACK)
  1099. { // Ignore ACK in SYN_SENT
  1100. }
  1101. else if (tcpflags == TcpHeader::SYN)
  1102. { // Received SYN, move to SYN_RCVD state and respond with SYN+ACK
  1103. NS_LOG_INFO ("SYN_SENT -> SYN_RCVD");
  1104. m_state = SYN_RCVD;
  1105. m_cnCount = m_cnRetries;
  1106. m_rxBuffer.SetNextRxSequence (tcpHeader.GetSequenceNumber () + SequenceNumber32 (1));
  1107. SendEmptyPacket (TcpHeader::SYN | TcpHeader::ACK);
  1108. }
  1109. else if (tcpflags == (TcpHeader::SYN | TcpHeader::ACK)
  1110. && m_nextTxSequence + SequenceNumber32 (1) == tcpHeader.GetAckNumber ())
  1111. { // Handshake completed
  1112. NS_LOG_INFO ("SYN_SENT -> ESTABLISHED");
  1113. m_state = ESTABLISHED;
  1114. m_connected = true;
  1115. m_retxEvent.Cancel ();
  1116. m_rxBuffer.SetNextRxSequence (tcpHeader.GetSequenceNumber () + SequenceNumber32 (1));
  1117. m_highTxMark = ++m_nextTxSequence;
  1118. m_txBuffer.SetHeadSequence (m_nextTxSequence);
  1119. SendEmptyPacket (TcpHeader::ACK);
  1120. SendPendingData (m_connected);
  1121. Simulator::ScheduleNow (&TcpSocketBase::ConnectionSucceeded, this);
  1122. // Always respond to first data packet to speed up the connection.
  1123. // Remove to get the behaviour of old NS-3 code.
  1124. m_delAckCount = m_delAckMaxCount;
  1125. }
  1126. else
  1127. { // Other in-sequence input
  1128. if (tcpflags != TcpHeader::RST)
  1129. { // When (1) rx of FIN+ACK; (2) rx of FIN; (3) rx of bad flags
  1130. NS_LOG_LOGIC ("Illegal flag " << std::hex << static_cast<uint32_t> (tcpflags) << std::dec << " received. Reset packet is sent.");
  1131. SendRST ();
  1132. }
  1133. CloseAndNotify ();
  1134. }
  1135. }
  1136. /* Received a packet upon SYN_RCVD */
  1137. void
  1138. TcpSocketBase::ProcessSynRcvd (Ptr<Packet> packet, const TcpHeader& tcpHeader,
  1139. const Address& fromAddress, const Address& toAddress)
  1140. {
  1141. NS_LOG_FUNCTION (this << tcpHeader);
  1142. // Extract the flags. PSH and URG are not honoured.
  1143. uint8_t tcpflags = tcpHeader.GetFlags () & ~(TcpHeader::PSH | TcpHeader::URG);
  1144. if (tcpflags == 0
  1145. || (tcpflags == TcpHeader::ACK
  1146. && m_nextTxSequence + SequenceNumber32 (1) == tcpHeader.GetAckNumber ()))
  1147. { // If it is bare data, accept it and move to ESTABLISHED state. This is
  1148. // possibly due to ACK lost in 3WHS. If in-sequence ACK is received, the
  1149. // handshake is completed nicely.
  1150. NS_LOG_INFO ("SYN_RCVD -> ESTABLISHED");
  1151. m_state = ESTABLISHED;
  1152. m_connected = true;
  1153. m_retxEvent.Cancel ();
  1154. m_highTxMark = ++m_nextTxSequence;
  1155. m_txBuffer.SetHeadSequence (m_nextTxSequence);
  1156. if (m_endPoint)
  1157. {
  1158. m_endPoint->SetPeer (InetSocketAddress::ConvertFrom (fromAddress).GetIpv4 (),
  1159. InetSocketAddress::ConvertFrom (fromAddress).GetPort ());
  1160. }
  1161. else if (m_endPoint6)
  1162. {
  1163. m_endPoint6->SetPeer (Inet6SocketAddress::ConvertFrom (fromAddress).GetIpv6 (),
  1164. Inet6SocketAddress::ConvertFrom (fromAddress).GetPort ());
  1165. }
  1166. // Always respond to first data packet to speed up the connection.
  1167. // Remove to get the behaviour of old NS-3 code.
  1168. m_delAckCount = m_delAckMaxCount;
  1169. ReceivedAck (packet, tcpHeader);
  1170. NotifyNewConnectionCreated (this, fromAddress);
  1171. // As this connection is established, the socket is available to send data now
  1172. if (GetTxAvailable () > 0)
  1173. {
  1174. NotifySend (GetTxAvailable ());
  1175. }
  1176. }
  1177. else if (tcpflags == TcpHeader::SYN)
  1178. { // Probably the peer lost my SYN+ACK
  1179. m_rxBuffer.SetNextRxSequence (tcpHeader.GetSequenceNumber () + SequenceNumber32 (1));
  1180. SendEmptyPacket (TcpHeader::SYN | TcpHeader::ACK);
  1181. }
  1182. else if (tcpflags == (TcpHeader::FIN | TcpHeader::ACK))
  1183. {
  1184. if (tcpHeader.GetSequenceNumber () == m_rxBuffer.NextRxSequence ())
  1185. { // In-sequence FIN before connection complete. Set up connection and close.
  1186. m_connected = true;
  1187. m_retxEvent.Cancel ();
  1188. m_highTxMark = ++m_nextTxSequence;
  1189. m_txBuffer.SetHeadSequence (m_nextTxSequence);
  1190. if (m_endPoint)
  1191. {
  1192. m_endPoint->SetPeer (InetSocketAddress::ConvertFrom (fromAddress).GetIpv4 (),
  1193. InetSocketAddress::ConvertFrom (fromAddress).GetPort ());
  1194. }
  1195. else if (m_endPoint6)
  1196. {
  1197. m_endPoint6->SetPeer (Inet6SocketAddress::ConvertFrom (fromAddress).GetIpv6 (),
  1198. Inet6SocketAddress::ConvertFrom (fromAddress).GetPort ());
  1199. }
  1200. PeerClose (packet, tcpHeader);
  1201. }
  1202. }
  1203. else
  1204. { // Other in-sequence input
  1205. if (tcpflags != TcpHeader::RST)
  1206. { // When (1) rx of SYN+ACK; (2) rx of FIN; (3) rx of bad flags
  1207. NS_LOG_LOGIC ("Illegal flag " << tcpflags << " received. Reset packet is sent.");
  1208. if (m_endPoint)
  1209. {
  1210. m_endPoint->SetPeer (InetSocketAddress::ConvertFrom (fromAddress).GetIpv4 (),
  1211. InetSocketAddress::ConvertFrom (fromAddress).GetPort ());
  1212. }
  1213. else if (m_endPoint6)
  1214. {
  1215. m_endPoint6->SetPeer (Inet6SocketAddress::ConvertFrom (fromAddress).GetIpv6 (),
  1216. Inet6SocketAddress::ConvertFrom (fromAddress).GetPort ());
  1217. }
  1218. SendRST ();
  1219. }
  1220. CloseAndNotify ();
  1221. }
  1222. }
  1223. /* Received a packet upon CLOSE_WAIT, FIN_WAIT_1, or FIN_WAIT_2 states */
  1224. void
  1225. TcpSocketBase::ProcessWait (Ptr<Packet> packet, const TcpHeader& tcpHeader)
  1226. {
  1227. NS_LOG_FUNCTION (this << tcpHeader);
  1228. // Extract the flags. PSH and URG are not honoured.
  1229. uint8_t tcpflags = tcpHeader.GetFlags () & ~(TcpHeader::PSH | TcpHeader::URG);
  1230. if (packet->GetSize () > 0 && tcpflags != TcpHeader::ACK)
  1231. { // Bare data, accept it
  1232. ReceivedData (packet, tcpHeader);
  1233. }
  1234. else if (tcpflags == TcpHeader::ACK)
  1235. { // Process the ACK, and if in FIN_WAIT_1, conditionally move to FIN_WAIT_2
  1236. ReceivedAck (packet, tcpHeader);
  1237. if (m_state == FIN_WAIT_1 && m_txBuffer.Size () == 0
  1238. && tcpHeader.GetAckNumber () == m_highTxMark + SequenceNumber32 (1))
  1239. { // This ACK corresponds to the FIN sent
  1240. NS_LOG_INFO ("FIN_WAIT_1 -> FIN_WAIT_2");
  1241. m_state = FIN_WAIT_2;
  1242. }
  1243. }
  1244. else if (tcpflags == TcpHeader::FIN || tcpflags == (TcpHeader::FIN | TcpHeader::ACK))
  1245. { // Got FIN, respond with ACK and move to next state
  1246. if (tcpflags & TcpHeader::ACK)
  1247. { // Process the ACK first
  1248. ReceivedAck (packet, tcpHeader);
  1249. }
  1250. m_rxBuffer.SetFinSequence (tcpHeader.GetSequenceNumber ());
  1251. }
  1252. else if (tcpflags == TcpHeader::SYN || tcpflags == (TcpHeader::SYN | TcpHeader::ACK))
  1253. { // Duplicated SYN or SYN+ACK, possibly due to spurious retransmission
  1254. return;
  1255. }
  1256. else
  1257. { // This is a RST or bad flags
  1258. if (tcpflags != TcpHeader::RST)
  1259. {
  1260. NS_LOG_LOGIC ("Illegal flag " << tcpflags << " received. Reset packet is sent.");
  1261. SendRST ();
  1262. }
  1263. CloseAndNotify ();
  1264. return;
  1265. }
  1266. // Check if the close responder sent an in-sequence FIN, if so, respond ACK
  1267. if ((m_state == FIN_WAIT_1 || m_state == FIN_WAIT_2) && m_rxBuffer.Finished ())
  1268. {
  1269. if (m_state == FIN_WAIT_1)
  1270. {
  1271. NS_LOG_INFO ("FIN_WAIT_1 -> CLOSING");
  1272. m_state = CLOSING;
  1273. if (m_txBuffer.Size () == 0
  1274. && tcpHeader.GetAckNumber () == m_highTxMark + SequenceNumber32 (1))
  1275. { // This ACK corresponds to the FIN sent
  1276. TimeWait ();
  1277. }
  1278. }
  1279. else if (m_state == FIN_WAIT_2)
  1280. {
  1281. TimeWait ();
  1282. }
  1283. SendEmptyPacket (TcpHeader::ACK);
  1284. if (!m_shutdownRecv)
  1285. {
  1286. NotifyDataRecv ();
  1287. }
  1288. }
  1289. }
  1290. /* Received a packet upon CLOSING */
  1291. void
  1292. TcpSocketBase::ProcessClosing (Ptr<Packet> packet, const TcpHeader& tcpHeader)
  1293. {
  1294. NS_LOG_FUNCTION (this << tcpHeader);
  1295. // Extract the flags. PSH and URG are not honoured.
  1296. uint8_t tcpflags = tcpHeader.GetFlags () & ~(TcpHeader::PSH | TcpHeader::URG);
  1297. if (tcpflags == TcpHeader::ACK)
  1298. {
  1299. if (tcpHeader.GetSequenceNumber () == m_rxBuffer.NextRxSequence ())
  1300. { // This ACK corresponds to the FIN sent
  1301. TimeWait ();
  1302. }
  1303. }
  1304. else
  1305. { // CLOSING state means simultaneous close, i.e. no one is sending data to
  1306. // anyone. If anything other than ACK is received, respond with a reset.
  1307. if (tcpflags == TcpHeader::FIN || tcpflags == (TcpHeader::FIN | TcpHeader::ACK))
  1308. { // FIN from the peer as well. We can close immediately.
  1309. SendEmptyPacket (TcpHeader::ACK);
  1310. }
  1311. else if (tcpflags != TcpHeader::RST)
  1312. { // Receive of SYN or SYN+ACK or bad flags or pure data
  1313. NS_LOG_LOGIC ("Illegal flag " << tcpflags << " received. Reset packet is sent.");
  1314. SendRST ();
  1315. }
  1316. CloseAndNotify ();
  1317. }
  1318. }
  1319. /* Received a packet upon LAST_ACK */
  1320. void
  1321. TcpSocketBase::ProcessLastAck (Ptr<Packet> packet, const TcpHeader& tcpHeader)
  1322. {
  1323. NS_LOG_FUNCTION (this << tcpHeader);
  1324. // Extract the flags. PSH and URG are not honoured.
  1325. uint8_t tcpflags = tcpHeader.GetFlags () & ~(TcpHeader::PSH | TcpHeader::URG);
  1326. if (tcpflags == 0)
  1327. {
  1328. ReceivedData (packet, tcpHeader);
  1329. }
  1330. else if (tcpflags == TcpHeader::ACK)
  1331. {
  1332. if (tcpHeader.GetSequenceNumber () == m_rxBuffer.NextRxSequence ())
  1333. { // This ACK corresponds to the FIN sent. This socket closed peacefully.
  1334. CloseAndNotify ();
  1335. }
  1336. }
  1337. else if (tcpflags == TcpHeader::FIN)
  1338. { // Received FIN again, the peer probably lost the FIN+ACK
  1339. SendEmptyPacket (TcpHeader::FIN | TcpHeader::ACK);
  1340. }
  1341. else if (tcpflags == (TcpHeader::FIN | TcpHeader::ACK) || tcpflags == TcpHeader::RST)
  1342. {
  1343. CloseAndNotify ();
  1344. }
  1345. else
  1346. { // Received a SYN or SYN+ACK or bad flags
  1347. NS_LOG_LOGIC ("Illegal flag " << tcpflags << " received. Reset packet is sent.");
  1348. SendRST ();
  1349. CloseAndNotify ();
  1350. }
  1351. }
  1352. /* Peer sent me a FIN. Remember its sequence in rx buffer. */
  1353. void
  1354. TcpSocketBase::PeerClose (Ptr<Packet> p, const TcpHeader& tcpHeader)
  1355. {
  1356. NS_LOG_FUNCTION (this << tcpHeader);
  1357. // Ignore all out of range packets
  1358. if (tcpHeader.GetSequenceNumber () < m_rxBuffer.NextRxSequence ()
  1359. || tcpHeader.GetSequenceNumber () > m_rxBuffer.MaxRxSequence ())
  1360. {
  1361. return;
  1362. }
  1363. // For any case, remember the FIN position in rx buffer first
  1364. m_rxBuffer.SetFinSequence (tcpHeader.GetSequenceNumber () + SequenceNumber32 (p->GetSize ()));
  1365. NS_LOG_LOGIC ("Accepted FIN at seq " << tcpHeader.GetSequenceNumber () + SequenceNumber32 (p->GetSize ()));
  1366. // If there is any piggybacked data, process it
  1367. if (p->GetSize ())
  1368. {
  1369. ReceivedData (p, tcpHeader);
  1370. }
  1371. // Return if FIN is out of sequence, otherwise move to CLOSE_WAIT state by DoPeerClose
  1372. if (!m_rxBuffer.Finished ())
  1373. {
  1374. return;
  1375. }
  1376. // Simultaneous close: Application invoked Close() when we are processing this FIN packet
  1377. if (m_state == FIN_WAIT_1)
  1378. {
  1379. NS_LOG_INFO ("FIN_WAIT_1 -> CLOSING");
  1380. m_state = CLOSING;
  1381. return;
  1382. }
  1383. DoPeerClose (); // Change state, respond with ACK
  1384. }
  1385. /* Received a in-sequence FIN. Close down this socket. */
  1386. void
  1387. TcpSocketBase::DoPeerClose (void)
  1388. {
  1389. NS_ASSERT (m_state == ESTABLISHED || m_state == SYN_RCVD);
  1390. // Move the state to CLOSE_WAIT
  1391. NS_LOG_INFO (TcpStateName[m_state] << " -> CLOSE_WAIT");
  1392. m_state = CLOSE_WAIT;
  1393. if (!m_closeNotified)
  1394. {
  1395. // The normal behaviour for an application is that, when the peer sent a in-sequence
  1396. // FIN, the app should prepare to close. The app has two choices at this point: either
  1397. // respond with ShutdownSend() call to declare that it has nothing more to send and
  1398. // the socket can be closed immediately; or remember the peer's close request, wait
  1399. // until all its existing data are pushed into the TCP socket, then call Close()
  1400. // explicitly.
  1401. NS_LOG_LOGIC ("TCP " << this << " calling NotifyNormalClose");
  1402. NotifyNormalClose ();
  1403. m_closeNotified = true;
  1404. }
  1405. if (m_shutdownSend)
  1406. { // The application declares that it would not sent any more, close this socket
  1407. Close ();
  1408. }
  1409. else
  1410. { // Need to ack, the application will close later
  1411. SendEmptyPacket (TcpHeader::ACK);
  1412. }
  1413. if (m_state == LAST_ACK)
  1414. {
  1415. NS_LOG_LOGIC ("TcpSocketBase " << this << " scheduling LATO1");
  1416. m_lastAckEvent = Simulator::Schedule (m_rtt->RetransmitTimeout (),
  1417. &TcpSocketBase::LastAckTimeout, this);
  1418. }
  1419. }
  1420. /* Kill this socket. This is a callback function configured to m_endpoint in
  1421. SetupCallback(), invoked when the endpoint is destroyed. */
  1422. void
  1423. TcpSocketBase::Destroy (void)
  1424. {
  1425. NS_LOG_FUNCTION (this);
  1426. m_endPoint = 0;
  1427. if (m_tcp != 0)
  1428. {
  1429. std::vector<Ptr<TcpSocketBase> >::iterator it
  1430. = std::find (m_tcp->m_sockets.begin (), m_tcp->m_sockets.end (), this);
  1431. if (it != m_tcp->m_sockets.end ())
  1432. {
  1433. m_tcp->m_sockets.erase (it);
  1434. }
  1435. }
  1436. NS_LOG_LOGIC (this << " Cancelled ReTxTimeout event which was set to expire at " <<
  1437. (Simulator::Now () + Simulator::GetDelayLeft (m_retxEvent)).GetSeconds ());
  1438. CancelAllTimers ();
  1439. }
  1440. /* Kill this socket. This is a callback function configured to m_endpoint in
  1441. SetupCallback(), invoked when the endpoint is destroyed. */
  1442. void
  1443. TcpSocketBase::Destroy6 (void)
  1444. {
  1445. NS_LOG_FUNCTION (this);
  1446. m_endPoint6 = 0;
  1447. if (m_tcp != 0)
  1448. {
  1449. std::vector<Ptr<TcpSocketBase> >::iterator it
  1450. = std::find (m_tcp->m_sockets.begin (), m_tcp->m_sockets.end (), this);
  1451. if (it != m_tcp->m_sockets.end ())
  1452. {
  1453. m_tcp->m_sockets.erase (it);
  1454. }
  1455. }
  1456. NS_LOG_LOGIC (this << " Cancelled ReTxTimeout event which was set to expire at " <<
  1457. (Simulator::Now () + Simulator::GetDelayLeft (m_retxEvent)).GetSeconds ());
  1458. CancelAllTimers ();
  1459. }
  1460. /* Send an empty packet with specified TCP flags */
  1461. void
  1462. TcpSocketBase::SendEmptyPacket (uint8_t flags)
  1463. {
  1464. NS_LOG_FUNCTION (this << (uint32_t)flags);
  1465. Ptr<Packet> p = Create<Packet> ();
  1466. TcpHeader header;
  1467. SequenceNumber32 s = m_nextTxSequence;
  1468. /*
  1469. * Add tags for each socket option.
  1470. * Note that currently the socket adds both IPv4 tag and IPv6 tag
  1471. * if both options are set. Once the packet got to layer three, only
  1472. * the corresponding tags will be read.
  1473. */
  1474. if (IsManualIpTos ())
  1475. {
  1476. SocketIpTosTag ipTosTag;
  1477. ipTosTag.SetTos (GetIpTos ());
  1478. p->AddPacketTag (ipTosTag);
  1479. }
  1480. if (IsManualIpv6Tclass ())
  1481. {
  1482. SocketIpv6TclassTag ipTclassTag;
  1483. ipTclassTag.SetTclass (GetIpv6Tclass ());
  1484. p->AddPacketTag (ipTclassTag);
  1485. }
  1486. if (IsManualIpTtl ())
  1487. {
  1488. SocketIpTtlTag ipTtlTag;
  1489. ipTtlTag.SetTtl (GetIpTtl ());
  1490. p->AddPacketTag (ipTtlTag);
  1491. }
  1492. if (IsManualIpv6HopLimit ())
  1493. {
  1494. SocketIpv6HopLimitTag ipHopLimitTag;
  1495. ipHopLimitTag.SetHopLimit (GetIpv6HopLimit ());
  1496. p->AddPacketTag (ipHopLimitTag);
  1497. }
  1498. if (m_endPoint == 0 && m_endPoint6 == 0)
  1499. {
  1500. NS_LOG_WARN ("Failed to send empty packet due to null endpoint");
  1501. return;
  1502. }
  1503. if (flags & TcpHeader::FIN)
  1504. {
  1505. flags |= TcpHeader::ACK;
  1506. }
  1507. else if (m_state == FIN_WAIT_1 || m_state == LAST_ACK || m_state == CLOSING)
  1508. {
  1509. ++s;
  1510. }
  1511. header.SetFlags (flags);
  1512. header.SetSequenceNumber (s);
  1513. header.SetAckNumber (m_rxBuffer.NextRxSequence ());
  1514. if (m_endPoint != 0)
  1515. {
  1516. header.SetSourcePort (m_endPoint->GetLocalPort ());
  1517. header.SetDestinationPort (m_endPoint->GetPeerPort ());
  1518. }
  1519. else
  1520. {
  1521. header.SetSourcePort (m_endPoint6->GetLocalPort ());
  1522. header.SetDestinationPort (m_endPoint6->GetPeerPort ());
  1523. }
  1524. header.SetWindowSize (AdvertisedWindowSize ());
  1525. AddOptions (header);
  1526. m_rto = m_rtt->RetransmitTimeout ();
  1527. bool hasSyn = flags & TcpHeader::SYN;
  1528. bool hasFin = flags & TcpHeader::FIN;
  1529. bool isAck = flags == TcpHeader::ACK;
  1530. if (hasSyn)
  1531. {
  1532. if (m_cnCount == 0)
  1533. { // No more connection retries, give up
  1534. NS_LOG_LOGIC ("Connection failed.");
  1535. CloseAndNotify ();
  1536. return;
  1537. }
  1538. else
  1539. { // Exponential backoff of connection time out
  1540. int backoffCount = 0x1 << (m_cnRetries - m_cnCount);
  1541. m_rto = m_cnTimeout * backoffCount;
  1542. m_cnCount--;
  1543. }
  1544. }
  1545. if (m_endPoint != 0)
  1546. {
  1547. m_tcp->SendPacket (p, header, m_endPoint->GetLocalAddress (),
  1548. m_endPoint->GetPeerAddress (), m_boundnetdevice);
  1549. }
  1550. else
  1551. {
  1552. m_tcp->SendPacket (p, header, m_endPoint6->GetLocalAddress (),
  1553. m_endPoint6->GetPeerAddress (), m_boundnetdevice);
  1554. }
  1555. if (flags & TcpHeader::ACK)
  1556. { // If sending an ACK, cancel the delay ACK as well
  1557. m_delAckEvent.Cancel ();
  1558. m_delAckCount = 0;
  1559. }
  1560. if (m_retxEvent.IsExpired () && (hasSyn || hasFin) && !isAck )
  1561. { // Retransmit SYN / SYN+ACK / FIN / FIN+ACK to guard against lost
  1562. NS_LOG_LOGIC ("Schedule retransmission timeout at time "
  1563. << Simulator::Now ().GetSeconds () << " to expire at time "
  1564. << (Simulator::Now () + m_rto.Get ()).GetSeconds ());
  1565. m_retxEvent = Simulator::Schedule (m_rto, &TcpSocketBase::SendEmptyPacket, this, flags);
  1566. }
  1567. }
  1568. /* This function closes the endpoint completely. Called upon RST_TX action. */
  1569. void
  1570. TcpSocketBase::SendRST (void)
  1571. {
  1572. NS_LOG_FUNCTION (this);
  1573. SendEmptyPacket (TcpHeader::RST);
  1574. NotifyErrorClose ();
  1575. DeallocateEndPoint ();
  1576. }
  1577. /* Deallocate the end point and cancel all the timers */
  1578. void
  1579. TcpSocketBase::DeallocateEndPoint (void)
  1580. {
  1581. if (m_endPoint != 0)
  1582. {
  1583. m_endPoint->SetDestroyCallback (MakeNullCallback<void> ());
  1584. m_tcp->DeAllocate (m_endPoint);
  1585. m_endPoint = 0;
  1586. std::vector<Ptr<TcpSocketBase> >::iterator it
  1587. = std::find (m_tcp->m_sockets.begin (), m_tcp->m_sockets.end (), this);
  1588. if (it != m_tcp->m_sockets.end ())
  1589. {
  1590. m_tcp->m_sockets.erase (it);
  1591. }
  1592. CancelAllTimers ();
  1593. }
  1594. if (m_endPoint6 != 0)
  1595. {
  1596. m_endPoint6->SetDestroyCallback (MakeNullCallback<void> ());
  1597. m_tcp->DeAllocate (m_endPoint6);
  1598. m_endPoint6 = 0;
  1599. std::vector<Ptr<TcpSocketBase> >::iterator it
  1600. = std::find (m_tcp->m_sockets.begin (), m_tcp->m_sockets.end (), this);
  1601. if (it != m_tcp->m_sockets.end ())
  1602. {
  1603. m_tcp->m_sockets.erase (it);
  1604. }
  1605. CancelAllTimers ();
  1606. }
  1607. }
  1608. /* Configure the endpoint to a local address. Called by Connect() if Bind() didn't specify one. */
  1609. int
  1610. TcpSocketBase::SetupEndpoint ()
  1611. {
  1612. NS_LOG_FUNCTION (this);
  1613. Ptr<Ipv4> ipv4 = m_node->GetObject<Ipv4> ();
  1614. NS_ASSERT (ipv4 != 0);
  1615. if (ipv4->GetRoutingProtocol () == 0)
  1616. {
  1617. NS_FATAL_ERROR ("No Ipv4RoutingProtocol in the node");
  1618. }
  1619. // Create a dummy packet, then ask the routing function for the best output
  1620. // interface's address
  1621. Ipv4Header header;
  1622. header.SetDestination (m_endPoint->GetPeerAddress ());
  1623. Socket::SocketErrno errno_;
  1624. Ptr<Ipv4Route> route;
  1625. Ptr<NetDevice> oif = m_boundnetdevice;
  1626. route = ipv4->GetRoutingProtocol ()->RouteOutput (Ptr<Packet> (), header, oif, errno_);
  1627. if (route == 0)
  1628. {
  1629. NS_LOG_LOGIC ("Route to " << m_endPoint->GetPeerAddress () << " does not exist");
  1630. NS_LOG_ERROR (errno_);
  1631. m_errno = errno_;
  1632. return -1;
  1633. }
  1634. NS_LOG_LOGIC ("Route exists");
  1635. m_endPoint->SetLocalAddress (route->GetSource ());
  1636. return 0;
  1637. }
  1638. int
  1639. TcpSocketBase::SetupEndpoint6 ()
  1640. {
  1641. NS_LOG_FUNCTION (this);
  1642. Ptr<Ipv6L3Protocol> ipv6 = m_node->GetObject<Ipv6L3Protocol> ();
  1643. NS_ASSERT (ipv6 != 0);
  1644. if (ipv6->GetRoutingProtocol () == 0)
  1645. {
  1646. NS_FATAL_ERROR ("No Ipv6RoutingProtocol in the node");
  1647. }
  1648. // Create a dummy packet, then ask the routing function for the best output
  1649. // interface's address
  1650. Ipv6Header header;
  1651. header.SetDestinationAddress (m_endPoint6->GetPeerAddress ());
  1652. Socket::SocketErrno errno_;
  1653. Ptr<Ipv6Route> route;
  1654. Ptr<NetDevice> oif = m_boundnetdevice;
  1655. route = ipv6->GetRoutingProtocol ()->RouteOutput (Ptr<Packet> (), header, oif, errno_);
  1656. if (route == 0)
  1657. {
  1658. NS_LOG_LOGIC ("Route to " << m_endPoint6->GetPeerAddress () << " does not exist");
  1659. NS_LOG_ERROR (errno_);
  1660. m_errno = errno_;
  1661. return -1;
  1662. }
  1663. NS_LOG_LOGIC ("Route exists");
  1664. m_endPoint6->SetLocalAddress (route->GetSource ());
  1665. return 0;
  1666. }
  1667. /* This function is called only if a SYN received in LISTEN state. After
  1668. TcpSocketBase cloned, allocate a new end point to handle the incoming
  1669. connection and send a SYN+ACK to complete the handshake. */
  1670. void
  1671. TcpSocketBase::CompleteFork (Ptr<Packet> p, const TcpHeader& h,
  1672. const Address& fromAddress, const Address& toAddress)
  1673. {
  1674. // Get port and address from peer (connecting host)
  1675. if (InetSocketAddress::IsMatchingType (toAddress))
  1676. {
  1677. m_endPoint = m_tcp->Allocate (InetSocketAddress::ConvertFrom (toAddress).GetIpv4 (),
  1678. InetSocketAddress::ConvertFrom (toAddress).GetPort (),
  1679. InetSocketAddress::ConvertFrom (fromAddress).GetIpv4 (),
  1680. InetSocketAddress::ConvertFrom (fromAddress).GetPort ());
  1681. m_endPoint6 = 0;
  1682. }
  1683. else if (Inet6SocketAddress::IsMatchingType (toAddress))
  1684. {
  1685. m_endPoint6 = m_tcp->Allocate6 (Inet6SocketAddress::ConvertFrom (toAddress).GetIpv6 (),
  1686. Inet6SocketAddress::ConvertFrom (toAddress).GetPort (),
  1687. Inet6SocketAddress::ConvertFrom (fromAddress).GetIpv6 (),
  1688. Inet6SocketAddress::ConvertFrom (fromAddress).GetPort ());
  1689. m_endPoint = 0;
  1690. }
  1691. m_tcp->m_sockets.push_back (this);
  1692. // Change the cloned socket from LISTEN state to SYN_RCVD
  1693. NS_LOG_INFO ("LISTEN -> SYN_RCVD");
  1694. m_state = SYN_RCVD;
  1695. m_cnCount = m_cnRetries;
  1696. SetupCallback ();
  1697. // Set the sequence number and send SYN+ACK
  1698. m_rxBuffer.SetNextRxSequence (h.GetSequenceNumber () + SequenceNumber32 (1));
  1699. SendEmptyPacket (TcpHeader::SYN | TcpHeader::ACK);
  1700. }
  1701. void
  1702. TcpSocketBase::ConnectionSucceeded ()
  1703. { // Wrapper to protected function NotifyConnectionSucceeded() so that it can
  1704. // be called as a scheduled event
  1705. NotifyConnectionSucceeded ();
  1706. // The if-block below was moved from ProcessSynSent() to here because we need
  1707. // to invoke the NotifySend() only after NotifyConnectionSucceeded() to
  1708. // reflect the behaviour in the real world.
  1709. if (GetTxAvailable () > 0)
  1710. {
  1711. NotifySend (GetTxAvailable ());
  1712. }
  1713. }
  1714. /* Extract at most maxSize bytes from the TxBuffer at sequence seq, add the
  1715. TCP header, and send to TcpL4Protocol */
  1716. uint32_t
  1717. TcpSocketBase::SendDataPacket (SequenceNumber32 seq, uint32_t maxSize, bool withAck)
  1718. {
  1719. NS_LOG_FUNCTION (this << seq << maxSize << withAck);
  1720. Ptr<Packet> p = m_txBuffer.CopyFromSequence (maxSize, seq);
  1721. uint32_t sz = p->GetSize (); // Size of packet
  1722. uint8_t flags = withAck ? TcpHeader::ACK : 0;
  1723. uint32_t remainingData = m_txBuffer.SizeFromSequence (seq + SequenceNumber32 (sz));
  1724. /*
  1725. * Add tags for each socket option.
  1726. * Note that currently the socket adds both IPv4 tag and IPv6 tag
  1727. * if both options are set. Once the packet got to layer three, only
  1728. * the corresponding tags will be read.
  1729. */
  1730. if (IsManualIpTos ())
  1731. {
  1732. SocketIpTosTag ipTosTag;
  1733. ipTosTag.SetTos (GetIpTos ());
  1734. p->AddPacketTag (ipTosTag);
  1735. }
  1736. if (IsManualIpv6Tclass ())
  1737. {
  1738. SocketIpv6TclassTag ipTclassTag;
  1739. ipTclassTag.SetTclass (GetIpv6Tclass ());
  1740. p->AddPacketTag (ipTclassTag);
  1741. }
  1742. if (IsManualIpTtl ())
  1743. {
  1744. SocketIpTtlTag ipTtlTag;
  1745. ipTtlTag.SetTtl (GetIpTtl ());
  1746. p->AddPacketTag (ipTtlTag);
  1747. }
  1748. if (IsManualIpv6HopLimit ())
  1749. {
  1750. SocketIpv6HopLimitTag ipHopLimitTag;
  1751. ipHopLimitTag.SetHopLimit (GetIpv6HopLimit ());
  1752. p->AddPacketTag (ipHopLimitTag);
  1753. }
  1754. if (m_closeOnEmpty && (remainingData == 0))
  1755. {
  1756. flags |= TcpHeader::FIN;
  1757. if (m_state == ESTABLISHED)
  1758. { // On active close: I am the first one to send FIN
  1759. NS_LOG_INFO ("ESTABLISHED -> FIN_WAIT_1");
  1760. m_state = FIN_WAIT_1;
  1761. }
  1762. else if (m_state == CLOSE_WAIT)
  1763. { // On passive close: Peer sent me FIN already
  1764. NS_LOG_INFO ("CLOSE_WAIT -> LAST_ACK");
  1765. m_state = LAST_ACK;
  1766. }
  1767. }
  1768. TcpHeader header;
  1769. header.SetFlags (flags);
  1770. header.SetSequenceNumber (seq);
  1771. header.SetAckNumber (m_rxBuffer.NextRxSequence ());
  1772. if (m_endPoint)
  1773. {
  1774. header.SetSourcePort (m_endPoint->GetLocalPort ());
  1775. header.SetDestinationPort (m_endPoint->GetPeerPort ());
  1776. }
  1777. else
  1778. {
  1779. header.SetSourcePort (m_endPoint6->GetLocalPort ());
  1780. header.SetDestinationPort (m_endPoint6->GetPeerPort ());
  1781. }
  1782. header.SetWindowSize (AdvertisedWindowSize ());
  1783. AddOptions (header);
  1784. if (m_retxEvent.IsExpired () )
  1785. { // Schedule retransmit
  1786. m_rto = m_rtt->RetransmitTimeout ();
  1787. NS_LOG_LOGIC (this << " SendDataPacket Schedule ReTxTimeout at time " <<
  1788. Simulator::Now ().GetSeconds () << " to expire at time " <<
  1789. (Simulator::Now () + m_rto.Get ()).GetSeconds () );
  1790. m_retxEvent = Simulator::Schedule (m_rto, &TcpSocketBase::ReTxTimeout, this);
  1791. }
  1792. NS_LOG_LOGIC ("Send packet via TcpL4Protocol with flags 0x" << std::hex << static_cast<uint32_t> (flags) << std::dec);
  1793. if (m_endPoint)
  1794. {
  1795. m_tcp->SendPacket (p, header, m_endPoint->GetLocalAddress (),
  1796. m_endPoint->GetPeerAddress (), m_boundnetdevice);
  1797. }
  1798. else
  1799. {
  1800. m_tcp->SendPacket (p, header, m_endPoint6->GetLocalAddress (),
  1801. m_endPoint6->GetPeerAddress (), m_boundnetdevice);
  1802. }
  1803. m_rtt->SentSeq (seq, sz); // notify the RTT
  1804. // Notify the application of the data being sent unless this is a retransmit
  1805. if (seq == m_nextTxSequence)
  1806. {
  1807. Simulator::ScheduleNow (&TcpSocketBase::NotifyDataSent, this, sz);
  1808. }
  1809. // Update highTxMark
  1810. m_highTxMark = std::max (seq + sz, m_highTxMark.Get ());
  1811. return sz;
  1812. }
  1813. /* Send as much pending data as possible according to the Tx window. Note that
  1814. * this function did not implement the PSH flag
  1815. */
  1816. bool
  1817. TcpSocketBase::SendPendingData (bool withAck)
  1818. {
  1819. NS_LOG_FUNCTION (this << withAck);
  1820. if (m_txBuffer.Size () == 0)
  1821. {
  1822. return false; // Nothing to send
  1823. }
  1824. if (m_endPoint == 0 && m_endPoint6 == 0)
  1825. {
  1826. NS_LOG_INFO ("TcpSocketBase::SendPendingData: No endpoint; m_shutdownSend=" << m_shutdownSend);
  1827. return false; // Is this the right way to handle this condition?
  1828. }
  1829. uint32_t nPacketsSent = 0;
  1830. while (m_txBuffer.SizeFromSequence (m_nextTxSequence))
  1831. {
  1832. uint32_t w = AvailableWindow (); // Get available window size
  1833. NS_LOG_LOGIC ("TcpSocketBase " << this << " SendPendingData" <<
  1834. " w " << w <<
  1835. " rxwin " << m_rWnd <<
  1836. " segsize " << m_segmentSize <<
  1837. " nextTxSeq " << m_nextTxSequence <<
  1838. " highestRxAck " << m_txBuffer.HeadSequence () <<
  1839. " pd->Size " << m_txBuffer.Size () <<
  1840. " pd->SFS " << m_txBuffer.SizeFromSequence (m_nextTxSequence));
  1841. // Stop sending if we need to wait for a larger Tx window (prevent silly window syndrome)
  1842. if (w < m_segmentSize && m_txBuffer.SizeFromSequence (m_nextTxSequence) > w)
  1843. {
  1844. break; // No more
  1845. }
  1846. // Nagle's algorithm (RFC896): Hold off sending if there is unacked data
  1847. // in the buffer and the amount of data to send is less than one segment
  1848. if (!m_noDelay && UnAckDataCount () > 0
  1849. && m_txBuffer.SizeFromSequence (m_nextTxSequence) < m_segmentSize)
  1850. {
  1851. NS_LOG_LOGIC ("Invoking Nagle's algorithm. Wait to send.");
  1852. break;
  1853. }
  1854. uint32_t s = std::min (w, m_segmentSize); // Send no more than window
  1855. uint32_t sz = SendDataPacket (m_nextTxSequence, s, withAck);
  1856. nPacketsSent++; // Count sent this loop
  1857. m_nextTxSequence += sz; // Advance next tx sequence
  1858. }
  1859. NS_LOG_LOGIC ("SendPendingData sent " << nPacketsSent << " packets");
  1860. return (nPacketsSent > 0);
  1861. }
  1862. uint32_t
  1863. TcpSocketBase::UnAckDataCount ()
  1864. {
  1865. NS_LOG_FUNCTION (this);
  1866. return m_nextTxSequence.Get () - m_txBuffer.HeadSequence ();
  1867. }
  1868. uint32_t
  1869. TcpSocketBase::BytesInFlight ()
  1870. {
  1871. NS_LOG_FUNCTION (this);
  1872. return m_highTxMark.Get () - m_txBuffer.HeadSequence ();
  1873. }
  1874. uint32_t
  1875. TcpSocketBase::Window ()
  1876. {
  1877. NS_LOG_FUNCTION (this);
  1878. return m_rWnd;
  1879. }
  1880. uint32_t
  1881. TcpSocketBase::AvailableWindow ()
  1882. {
  1883. NS_LOG_FUNCTION_NOARGS ();
  1884. uint32_t unack = UnAckDataCount (); // Number of outstanding bytes
  1885. uint32_t win = Window (); // Number of bytes allowed to be outstanding
  1886. NS_LOG_LOGIC ("UnAckCount=" << unack << ", Win=" << win);
  1887. return (win < unack) ? 0 : (win - unack);
  1888. }
  1889. uint16_t
  1890. TcpSocketBase::AdvertisedWindowSize ()
  1891. {
  1892. return std::min (m_rxBuffer.MaxBufferSize () - m_rxBuffer.Size (), (uint32_t)m_maxWinSize);
  1893. }
  1894. // Receipt of new packet, put into Rx buffer
  1895. void
  1896. TcpSocketBase::ReceivedData (Ptr<Packet> p, const TcpHeader& tcpHeader)
  1897. {
  1898. NS_LOG_FUNCTION (this << tcpHeader);
  1899. NS_LOG_LOGIC ("seq " << tcpHeader.GetSequenceNumber () <<
  1900. " ack " << tcpHeader.GetAckNumber () <<
  1901. " pkt size " << p->GetSize () );
  1902. // Put into Rx buffer
  1903. SequenceNumber32 expectedSeq = m_rxBuffer.NextRxSequence ();
  1904. if (!m_rxBuffer.Add (p, tcpHeader))
  1905. { // Insert failed: No data or RX buffer full
  1906. SendEmptyPacket (TcpHeader::ACK);
  1907. return;
  1908. }
  1909. // Now send a new ACK packet acknowledging all received and delivered data
  1910. if (m_rxBuffer.Size () > m_rxBuffer.Available () || m_rxBuffer.NextRxSequence () > expectedSeq + p->GetSize ())
  1911. { // A gap exists in the buffer, or we filled a gap: Always ACK
  1912. SendEmptyPacket (TcpHeader::ACK);
  1913. }
  1914. else
  1915. { // In-sequence packet: ACK if delayed ack count allows
  1916. if (++m_delAckCount >= m_delAckMaxCount)
  1917. {
  1918. m_delAckEvent.Cancel ();
  1919. m_delAckCount = 0;
  1920. SendEmptyPacket (TcpHeader::ACK);
  1921. }
  1922. else if (m_delAckEvent.IsExpired ())
  1923. {
  1924. m_delAckEvent = Simulator::Schedule (m_delAckTimeout,
  1925. &TcpSocketBase::DelAckTimeout, this);
  1926. NS_LOG_LOGIC (this << " scheduled delayed ACK at " << (Simulator::Now () + Simulator::GetDelayLeft (m_delAckEvent)).GetSeconds ());
  1927. }
  1928. }
  1929. // Notify app to receive if necessary
  1930. if (expectedSeq < m_rxBuffer.NextRxSequence ())
  1931. { // NextRxSeq advanced, we have something to send to the app
  1932. if (!m_shutdownRecv)
  1933. {
  1934. NotifyDataRecv ();
  1935. }
  1936. // Handle exceptions
  1937. if (m_closeNotified)
  1938. {
  1939. NS_LOG_WARN ("Why TCP " << this << " got data after close notification?");
  1940. }
  1941. // If we received FIN before and now completed all "holes" in rx buffer,
  1942. // invoke peer close procedure
  1943. if (m_rxBuffer.Finished () && (tcpHeader.GetFlags () & TcpHeader::FIN) == 0)
  1944. {
  1945. DoPeerClose ();
  1946. }
  1947. }
  1948. }
  1949. /* Called by ForwardUp() to estimate RTT */
  1950. void
  1951. TcpSocketBase::EstimateRtt (const TcpHeader& tcpHeader)
  1952. {
  1953. // Use m_rtt for the estimation. Note, RTT of duplicated acknowledgement
  1954. // (which should be ignored) is handled by m_rtt. Once timestamp option
  1955. // is implemented, this function would be more elaborated.
  1956. Time nextRtt = m_rtt->AckSeq (tcpHeader.GetAckNumber () );
  1957. //nextRtt will be zero for dup acks. Don't want to update lastRtt in that case
  1958. //but still needed to do list clearing that is done in AckSeq.
  1959. if(nextRtt != Time (0))
  1960. {
  1961. m_lastRtt = nextRtt;
  1962. NS_LOG_FUNCTION(this << m_lastRtt);
  1963. }
  1964. }
  1965. // Called by the ReceivedAck() when new ACK received and by ProcessSynRcvd()
  1966. // when the three-way handshake completed. This cancels retransmission timer
  1967. // and advances Tx window
  1968. void
  1969. TcpSocketBase::NewAck (SequenceNumber32 const& ack)
  1970. {
  1971. NS_LOG_FUNCTION (this << ack);
  1972. if (m_state != SYN_RCVD)
  1973. { // Set RTO unless the ACK is received in SYN_RCVD state
  1974. NS_LOG_LOGIC (this << " Cancelled ReTxTimeout event which was set to expire at " <<
  1975. (Simulator::Now () + Simulator::GetDelayLeft (m_retxEvent)).GetSeconds ());
  1976. m_retxEvent.Cancel ();
  1977. // On recieving a "New" ack we restart retransmission timer .. RFC 2988
  1978. m_rto = m_rtt->RetransmitTimeout ();
  1979. NS_LOG_LOGIC (this << " Schedule ReTxTimeout at time " <<
  1980. Simulator::Now ().GetSeconds () << " to expire at time " <<
  1981. (Simulator::Now () + m_rto.Get ()).GetSeconds ());
  1982. m_retxEvent = Simulator::Schedule (m_rto, &TcpSocketBase::ReTxTimeout, this);
  1983. }
  1984. if (m_rWnd.Get () == 0 && m_persistEvent.IsExpired ())
  1985. { // Zero window: Enter persist state to send 1 byte to probe
  1986. NS_LOG_LOGIC (this << "Enter zerowindow persist state");
  1987. NS_LOG_LOGIC (this << "Cancelled ReTxTimeout event which was set to expire at " <<
  1988. (Simulator::Now () + Simulator::GetDelayLeft (m_retxEvent)).GetSeconds ());
  1989. m_retxEvent.Cancel ();
  1990. NS_LOG_LOGIC ("Schedule persist timeout at time " <<
  1991. Simulator::Now ().GetSeconds () << " to expire at time " <<
  1992. (Simulator::Now () + m_persistTimeout).GetSeconds ());
  1993. m_persistEvent = Simulator::Schedule (m_persistTimeout, &TcpSocketBase::PersistTimeout, this);
  1994. NS_ASSERT (m_persistTimeout == Simulator::GetDelayLeft (m_persistEvent));
  1995. }
  1996. // Note the highest ACK and tell app to send more
  1997. NS_LOG_LOGIC ("TCP " << this << " NewAck " << ack <<
  1998. " numberAck " << (ack - m_txBuffer.HeadSequence ())); // Number bytes ack'ed
  1999. m_txBuffer.DiscardUpTo (ack);
  2000. if (GetTxAvailable () > 0)
  2001. {
  2002. NotifySend (GetTxAvailable ());
  2003. }
  2004. if (ack > m_nextTxSequence)
  2005. {
  2006. m_nextTxSequence = ack; // If advanced
  2007. }
  2008. if (m_txBuffer.Size () == 0 && m_state != FIN_WAIT_1 && m_state != CLOSING)
  2009. { // No retransmit timer if no data to retransmit
  2010. NS_LOG_LOGIC (this << " Cancelled ReTxTimeout event which was set to expire at " <<
  2011. (Simulator::Now () + Simulator::GetDelayLeft (m_retxEvent)).GetSeconds ());
  2012. m_retxEvent.Cancel ();
  2013. }
  2014. // Try to send more data
  2015. SendPendingData (m_connected);
  2016. }
  2017. // Retransmit timeout
  2018. void
  2019. TcpSocketBase::ReTxTimeout ()
  2020. {
  2021. NS_LOG_FUNCTION (this);
  2022. NS_LOG_LOGIC (this << " ReTxTimeout Expired at time " << Simulator::Now ().GetSeconds ());
  2023. // If erroneous timeout in closed/timed-wait state, just return
  2024. if (m_state == CLOSED || m_state == TIME_WAIT)
  2025. {
  2026. return;
  2027. }
  2028. // If all data are received (non-closing socket and nothing to send), just return
  2029. if (m_state <= ESTABLISHED && m_txBuffer.HeadSequence () >= m_highTxMark)
  2030. {
  2031. return;
  2032. }
  2033. Retransmit ();
  2034. }
  2035. void
  2036. TcpSocketBase::DelAckTimeout (void)
  2037. {
  2038. m_delAckCount = 0;
  2039. SendEmptyPacket (TcpHeader::ACK);
  2040. }
  2041. void
  2042. TcpSocketBase::LastAckTimeout (void)
  2043. {
  2044. NS_LOG_FUNCTION (this);
  2045. m_lastAckEvent.Cancel ();
  2046. if (m_state == LAST_ACK)
  2047. {
  2048. CloseAndNotify ();
  2049. }
  2050. if (!m_closeNotified)
  2051. {
  2052. m_closeNotified = true;
  2053. }
  2054. }
  2055. // Send 1-byte data to probe for the window size at the receiver when
  2056. // the local knowledge tells that the receiver has zero window size
  2057. // C.f.: RFC793 p.42, RFC1112 sec.4.2.2.17
  2058. void
  2059. TcpSocketBase::PersistTimeout ()
  2060. {
  2061. NS_LOG_LOGIC ("PersistTimeout expired at " << Simulator::Now ().GetSeconds ());
  2062. m_persistTimeout = std::min (Seconds (60), Time (2 * m_persistTimeout)); // max persist timeout = 60s
  2063. Ptr<Packet> p = m_txBuffer.CopyFromSequence (1, m_nextTxSequence);
  2064. TcpHeader tcpHeader;
  2065. tcpHeader.SetSequenceNumber (m_nextTxSequence);
  2066. tcpHeader.SetAckNumber (m_rxBuffer.NextRxSequence ());
  2067. tcpHeader.SetWindowSize (AdvertisedWindowSize ());
  2068. if (m_endPoint != 0)
  2069. {
  2070. tcpHeader.SetSourcePort (m_endPoint->GetLocalPort ());
  2071. tcpHeader.SetDestinationPort (m_endPoint->GetPeerPort ());
  2072. }
  2073. else
  2074. {
  2075. tcpHeader.SetSourcePort (m_endPoint6->GetLocalPort ());
  2076. tcpHeader.SetDestinationPort (m_endPoint6->GetPeerPort ());
  2077. }
  2078. AddOptions (tcpHeader);
  2079. if (m_endPoint != 0)
  2080. {
  2081. m_tcp->SendPacket (p, tcpHeader, m_endPoint->GetLocalAddress (),
  2082. m_endPoint->GetPeerAddress (), m_boundnetdevice);
  2083. }
  2084. else
  2085. {
  2086. m_tcp->SendPacket (p, tcpHeader, m_endPoint6->GetLocalAddress (),
  2087. m_endPoint6->GetPeerAddress (), m_boundnetdevice);
  2088. }
  2089. NS_LOG_LOGIC ("Schedule persist timeout at time "
  2090. << Simulator::Now ().GetSeconds () << " to expire at time "
  2091. << (Simulator::Now () + m_persistTimeout).GetSeconds ());
  2092. m_persistEvent = Simulator::Schedule (m_persistTimeout, &TcpSocketBase::PersistTimeout, this);
  2093. }
  2094. void
  2095. TcpSocketBase::Retransmit ()
  2096. {
  2097. m_nextTxSequence = m_txBuffer.HeadSequence (); // Start from highest Ack
  2098. m_rtt->IncreaseMultiplier (); // Double the timeout value for next retx timer
  2099. m_dupAckCount = 0;
  2100. DoRetransmit (); // Retransmit the packet
  2101. }
  2102. void
  2103. TcpSocketBase::DoRetransmit ()
  2104. {
  2105. NS_LOG_FUNCTION (this);
  2106. // Retransmit SYN packet
  2107. if (m_state == SYN_SENT)
  2108. {
  2109. if (m_cnCount > 0)
  2110. {
  2111. SendEmptyPacket (TcpHeader::SYN);
  2112. }
  2113. else
  2114. {
  2115. NotifyConnectionFailed ();
  2116. }
  2117. return;
  2118. }
  2119. // Retransmit non-data packet: Only if in FIN_WAIT_1 or CLOSING state
  2120. if (m_txBuffer.Size () == 0)
  2121. {
  2122. if (m_state == FIN_WAIT_1 || m_state == CLOSING)
  2123. { // Must have lost FIN, re-send
  2124. SendEmptyPacket (TcpHeader::FIN);
  2125. }
  2126. return;
  2127. }
  2128. // Retransmit a data packet: Call SendDataPacket
  2129. NS_LOG_LOGIC ("TcpSocketBase " << this << " retxing seq " << m_txBuffer.HeadSequence ());
  2130. uint32_t sz = SendDataPacket (m_txBuffer.HeadSequence (), m_segmentSize, true);
  2131. // In case of RTO, advance m_nextTxSequence
  2132. m_nextTxSequence = std::max (m_nextTxSequence.Get (), m_txBuffer.HeadSequence () + sz);
  2133. }
  2134. void
  2135. TcpSocketBase::CancelAllTimers ()
  2136. {
  2137. m_retxEvent.Cancel ();
  2138. m_persistEvent.Cancel ();
  2139. m_delAckEvent.Cancel ();
  2140. m_lastAckEvent.Cancel ();
  2141. m_timewaitEvent.Cancel ();
  2142. }
  2143. /* Move TCP to Time_Wait state and schedule a transition to Closed state */
  2144. void
  2145. TcpSocketBase::TimeWait ()
  2146. {
  2147. NS_LOG_INFO (TcpStateName[m_state] << " -> TIME_WAIT");
  2148. m_state = TIME_WAIT;
  2149. CancelAllTimers ();
  2150. // Move from TIME_WAIT to CLOSED after 2*MSL. Max segment lifetime is 2 min
  2151. // according to RFC793, p.28
  2152. m_timewaitEvent = Simulator::Schedule (Seconds (2 * m_msl),
  2153. &TcpSocketBase::CloseAndNotify, this);
  2154. }
  2155. /* Below are the attribute get/set functions */
  2156. void
  2157. TcpSocketBase::SetSndBufSize (uint32_t size)
  2158. {
  2159. m_txBuffer.SetMaxBufferSize (size);
  2160. }
  2161. uint32_t
  2162. TcpSocketBase::GetSndBufSize (void) const
  2163. {
  2164. return m_txBuffer.MaxBufferSize ();
  2165. }
  2166. void
  2167. TcpSocketBase::SetRcvBufSize (uint32_t size)
  2168. {
  2169. m_rxBuffer.SetMaxBufferSize (size);
  2170. }
  2171. uint32_t
  2172. TcpSocketBase::GetRcvBufSize (void) const
  2173. {
  2174. return m_rxBuffer.MaxBufferSize ();
  2175. }
  2176. void
  2177. TcpSocketBase::SetSegSize (uint32_t size)
  2178. {
  2179. m_segmentSize = size;
  2180. NS_ABORT_MSG_UNLESS (m_state == CLOSED, "Cannot change segment size dynamically.");
  2181. }
  2182. uint32_t
  2183. TcpSocketBase::GetSegSize (void) const
  2184. {
  2185. return m_segmentSize;
  2186. }
  2187. void
  2188. TcpSocketBase::SetConnTimeout (Time timeout)
  2189. {
  2190. m_cnTimeout = timeout;
  2191. }
  2192. Time
  2193. TcpSocketBase::GetConnTimeout (void) const
  2194. {
  2195. return m_cnTimeout;
  2196. }
  2197. void
  2198. TcpSocketBase::SetConnCount (uint32_t count)
  2199. {
  2200. m_cnRetries = count;
  2201. }
  2202. uint32_t
  2203. TcpSocketBase::GetConnCount (void) const
  2204. {
  2205. return m_cnRetries;
  2206. }
  2207. void
  2208. TcpSocketBase::SetDelAckTimeout (Time timeout)
  2209. {
  2210. m_delAckTimeout = timeout;
  2211. }
  2212. Time
  2213. TcpSocketBase::GetDelAckTimeout (void) const
  2214. {
  2215. return m_delAckTimeout;
  2216. }
  2217. void
  2218. TcpSocketBase::SetDelAckMaxCount (uint32_t count)
  2219. {
  2220. m_delAckMaxCount = count;
  2221. }
  2222. uint32_t
  2223. TcpSocketBase::GetDelAckMaxCount (void) const
  2224. {
  2225. return m_delAckMaxCount;
  2226. }
  2227. void
  2228. TcpSocketBase::SetTcpNoDelay (bool noDelay)
  2229. {
  2230. m_noDelay = noDelay;
  2231. }
  2232. bool
  2233. TcpSocketBase::GetTcpNoDelay (void) const
  2234. {
  2235. return m_noDelay;
  2236. }
  2237. void
  2238. TcpSocketBase::SetPersistTimeout (Time timeout)
  2239. {
  2240. m_persistTimeout = timeout;
  2241. }
  2242. Time
  2243. TcpSocketBase::GetPersistTimeout (void) const
  2244. {
  2245. return m_persistTimeout;
  2246. }
  2247. bool
  2248. TcpSocketBase::SetAllowBroadcast (bool allowBroadcast)
  2249. {
  2250. // Broadcast is not implemented. Return true only if allowBroadcast==false
  2251. return (!allowBroadcast);
  2252. }
  2253. bool
  2254. TcpSocketBase::GetAllowBroadcast (void) const
  2255. {
  2256. return false;
  2257. }
  2258. /* Placeholder function for future extension that reads more from the TCP header */
  2259. void
  2260. TcpSocketBase::ReadOptions (const TcpHeader&)
  2261. {
  2262. }
  2263. /* Placeholder function for future extension that changes the TCP header */
  2264. void
  2265. TcpSocketBase::AddOptions (TcpHeader&)
  2266. {
  2267. }
  2268. } // namespace ns3