PageRenderTime 61ms CodeModel.GetById 22ms RepoModel.GetById 0ms 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

Large files files are truncated, but you can click here to view the full file

  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

Large files files are truncated, but you can click here to view the full file