NS-3 based Named Data Networking (NDN) simulator
ndnSIM 2.5: NDN, CCN, CCNx, content centric networks
API Documentation
tcp-transport.cpp
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * Copyright (c) 2014-2018, Regents of the University of California,
4  * Arizona Board of Regents,
5  * Colorado State University,
6  * University Pierre & Marie Curie, Sorbonne University,
7  * Washington University in St. Louis,
8  * Beijing Institute of Technology,
9  * The University of Memphis.
10  *
11  * This file is part of NFD (Named Data Networking Forwarding Daemon).
12  * See AUTHORS.md for complete list of NFD authors and contributors.
13  *
14  * NFD is free software: you can redistribute it and/or modify it under the terms
15  * of the GNU General Public License as published by the Free Software Foundation,
16  * either version 3 of the License, or (at your option) any later version.
17  *
18  * NFD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
19  * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
20  * PURPOSE. See the GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License along with
23  * NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
24  */
25 
26 #include "tcp-transport.hpp"
27 
28 #if defined(__linux__)
29 #include <linux/sockios.h>
30 #include <sys/ioctl.h>
31 #endif
32 
33 namespace nfd {
34 namespace face {
35 
36 NFD_LOG_MEMBER_INIT_SPECIALIZED(StreamTransport<boost::asio::ip::tcp>, TcpTransport);
37 
38 time::milliseconds TcpTransport::s_initialReconnectWait = 1_s;
39 time::milliseconds TcpTransport::s_maxReconnectWait = 5_min;
40 float TcpTransport::s_reconnectWaitMultiplier = 2.0f;
41 
42 TcpTransport::TcpTransport(protocol::socket&& socket, ndn::nfd::FacePersistency persistency, ndn::nfd::FaceScope faceScope)
43  : StreamTransport(std::move(socket))
44  , m_remoteEndpoint(m_socket.remote_endpoint())
45  , m_nextReconnectWait(s_initialReconnectWait)
46 {
47  this->setLocalUri(FaceUri(m_socket.local_endpoint()));
48  this->setRemoteUri(FaceUri(m_socket.remote_endpoint()));
49  this->setScope(faceScope);
50  this->setPersistency(persistency);
52  this->setMtu(MTU_UNLIMITED);
53 
54  NFD_LOG_FACE_INFO("Creating transport");
55 }
56 
57 ssize_t
59 {
60  int queueLength = getSendQueueBytes();
61 
62  // We want to obtain the amount of "not sent" bytes instead of the amount of "not sent" + "not
63  // acked" bytes. On Linux, we use SIOCOUTQNSD for this reason. However, macOS does not provide an
64  // efficient mechanism to obtain this value (SO_NWRITE includes both "not sent" and "not acked").
65 #if defined(__linux__)
66  int nsd;
67  if (ioctl(m_socket.native_handle(), SIOCOUTQNSD, &nsd) < 0) {
68  NFD_LOG_FACE_WARN("Failed to obtain send queue length from socket: " << std::strerror(errno));
69  }
70  else if (nsd > 0) {
71  NFD_LOG_FACE_TRACE("SIOCOUTQNSD=" << nsd);
72  queueLength += nsd;
73  }
74 #endif
75 
76  return queueLength;
77 }
78 
79 bool
81 {
82  return true;
83 }
84 
85 void
87 {
88  // if persistency was changed from permanent to any other value
89  if (oldPersistency == ndn::nfd::FACE_PERSISTENCY_PERMANENT) {
90  if (this->getState() == TransportState::DOWN) {
91  // non-permanent transport cannot be in DOWN state, so fail hard
93  doClose();
94  }
95  }
96 }
97 
98 void
99 TcpTransport::handleError(const boost::system::error_code& error)
100 {
102  NFD_LOG_FACE_TRACE("TCP socket error: " << error.message());
104 
105  // cancel all outstanding operations
106  boost::system::error_code error;
107  m_socket.cancel(error);
108 
109  // do this asynchronously because there could be some callbacks still pending
110  getGlobalIoService().post([this] { reconnect(); });
111  }
112  else {
114  }
115 }
116 
117 void
118 TcpTransport::reconnect()
119 {
120  NFD_LOG_FACE_TRACE(__func__);
121 
125  // transport is shutting down, don't attempt to reconnect
126  return;
127  }
128 
130  BOOST_ASSERT(getState() == TransportState::DOWN);
131 
132  // recreate the socket
133  m_socket = protocol::socket(m_socket.get_io_service());
134  this->resetReceiveBuffer();
135  this->resetSendQueue();
136 
137  m_reconnectEvent = scheduler::schedule(m_nextReconnectWait, [this] { this->handleReconnectTimeout(); });
138  m_socket.async_connect(m_remoteEndpoint, [this] (const auto& e) { this->handleReconnect(e); });
139 }
140 
141 void
142 TcpTransport::handleReconnect(const boost::system::error_code& error)
143 {
147  error == boost::asio::error::operation_aborted) {
148  // transport is shutting down, abort the reconnection attempt and ignore any errors
149  return;
150  }
151 
152  if (error) {
153  NFD_LOG_FACE_TRACE("Reconnection attempt failed: " << error.message());
154  return;
155  }
156 
157  m_reconnectEvent.cancel();
158  m_nextReconnectWait = s_initialReconnectWait;
159 
160  this->setLocalUri(FaceUri(m_socket.local_endpoint()));
161  NFD_LOG_FACE_TRACE("TCP connection reestablished");
163  this->startReceive();
164 }
165 
166 void
167 TcpTransport::handleReconnectTimeout()
168 {
169  // abort the reconnection attempt
170  boost::system::error_code error;
171  m_socket.close(error);
172 
173  // exponentially back off the reconnection timer
174  m_nextReconnectWait =
175  std::min(time::duration_cast<time::milliseconds>(m_nextReconnectWait * s_reconnectWaitMultiplier),
176  s_maxReconnectWait);
177 
178  // do this asynchronously because there could be some callbacks still pending
179  getGlobalIoService().post([this] { reconnect(); });
180 }
181 
182 void
184 {
185  m_reconnectEvent.cancel();
187 }
188 
189 } // namespace face
190 } // namespace nfd
void afterChangePersistency(ndn::nfd::FacePersistency oldPersistency) final
invoked after the persistency has been changed
void setPersistency(ndn::nfd::FacePersistency newPersistency)
changes face persistency setting
Definition: transport.cpp:154
void doClose() override
performs Transport specific operations to close the transport
void doClose() final
performs Transport specific operations to close the transport
NFD_LOG_MEMBER_INIT_SPECIALIZED((DatagramTransport< boost::asio::ip::udp, Multicast >), MulticastUdpTransport)
#define NFD_LOG_FACE_TRACE(msg)
Log a message at TRACE level.
Definition: face-log.hpp:79
const ssize_t MTU_UNLIMITED
indicates the transport has no limit on payload size
Definition: transport.hpp:96
void setRemoteUri(const FaceUri &uri)
Definition: transport.hpp:433
virtual void handleError(const boost::system::error_code &error)
detail::SimulatorIo & getGlobalIoService()
Definition: global-io.cpp:48
void setLinkType(ndn::nfd::LinkType linkType)
Definition: transport.hpp:463
ssize_t getSendQueueLength() final
void setMtu(ssize_t mtu)
Definition: transport.hpp:475
Implements Transport for stream-based protocols.
the transport is being closed due to a failure
void setScope(ndn::nfd::FaceScope scope)
Definition: transport.hpp:445
#define NFD_LOG_FACE_INFO(msg)
Log a message at INFO level.
Definition: face-log.hpp:85
TransportState getState() const
Definition: transport.hpp:494
Copyright (c) 2011-2015 Regents of the University of California.
Definition: ndn-common.hpp:40
the transport is closed, and can be safely deallocated
void post(const std::function< void()> &callback)
Definition: global-io.cpp:34
void cancel()
Cancel the operation.
TcpTransport(protocol::socket &&socket, ndn::nfd::FacePersistency persistency, ndn::nfd::FaceScope faceScope)
void setLocalUri(const FaceUri &uri)
Definition: transport.hpp:421
void handleError(const boost::system::error_code &error) final
the transport is being closed gracefully, either by the peer or by a call to close()
represents the underlying protocol and address used by a Face
Definition: face-uri.hpp:44
ndn::nfd::FacePersistency getPersistency() const
Definition: transport.hpp:451
bool canChangePersistencyToImpl(ndn::nfd::FacePersistency newPersistency) const final
invoked by canChangePersistencyTo to perform the check
EventId schedule(time::nanoseconds after, const EventCallback &event)
Schedule an event.
Definition: scheduler.cpp:48
void setState(TransportState newState)
set transport state
Definition: transport.cpp:177
the transport is up and can transmit packets
#define NFD_LOG_FACE_WARN(msg)
Log a message at WARN level.
Definition: face-log.hpp:88
the transport is temporarily down, and is being recovered