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-2019, 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 #include "common/global.hpp"
28 
29 #if defined(__linux__)
30 #include <linux/sockios.h>
31 #include <sys/ioctl.h>
32 #endif
33 
34 namespace nfd {
35 namespace face {
36 
38 
39 time::milliseconds TcpTransport::s_initialReconnectWait = 1_s;
40 time::milliseconds TcpTransport::s_maxReconnectWait = 5_min;
41 float TcpTransport::s_reconnectWaitMultiplier = 2.0f;
42 
43 TcpTransport::TcpTransport(protocol::socket&& socket,
44  ndn::nfd::FacePersistency persistency,
45  ndn::nfd::FaceScope faceScope)
46  : StreamTransport(std::move(socket))
47  , m_remoteEndpoint(m_socket.remote_endpoint())
48  , m_nextReconnectWait(s_initialReconnectWait)
49 {
50  this->setLocalUri(FaceUri(m_socket.local_endpoint()));
51  this->setRemoteUri(FaceUri(m_socket.remote_endpoint()));
52  this->setScope(faceScope);
53  this->setPersistency(persistency);
55  this->setMtu(MTU_UNLIMITED);
56 
57  NFD_LOG_FACE_DEBUG("Creating transport");
58 }
59 
60 ssize_t
62 {
63  int queueLength = getSendQueueBytes();
64 
65  // We want to obtain the amount of "not sent" bytes instead of the amount of "not sent" + "not
66  // acked" bytes. On Linux, we use SIOCOUTQNSD for this reason. However, macOS does not provide an
67  // efficient mechanism to obtain this value (SO_NWRITE includes both "not sent" and "not acked").
68 #if defined(__linux__)
69  int nsd;
70  if (ioctl(m_socket.native_handle(), SIOCOUTQNSD, &nsd) < 0) {
71  NFD_LOG_FACE_WARN("Failed to obtain send queue length from socket: " << std::strerror(errno));
72  }
73  else if (nsd > 0) {
74  NFD_LOG_FACE_TRACE("SIOCOUTQNSD=" << nsd);
75  queueLength += nsd;
76  }
77 #endif
78 
79  return queueLength;
80 }
81 
82 bool
84 {
85  return true;
86 }
87 
88 void
90 {
91  // if persistency was changed from permanent to any other value
92  if (oldPersistency == ndn::nfd::FACE_PERSISTENCY_PERMANENT) {
93  if (this->getState() == TransportState::DOWN) {
94  // non-permanent transport cannot be in DOWN state, so fail hard
96  doClose();
97  }
98  }
99 }
100 
101 void
102 TcpTransport::handleError(const boost::system::error_code& error)
103 {
105  NFD_LOG_FACE_TRACE("TCP socket error: " << error.message());
107 
108  // cancel all outstanding operations
109  boost::system::error_code ec;
110  m_socket.cancel(ec);
111 
112  // do this asynchronously because there could be some callbacks still pending
113  getGlobalIoService().post([this] { reconnect(); });
114  }
115  else {
117  }
118 }
119 
120 void
121 TcpTransport::reconnect()
122 {
123  NFD_LOG_FACE_TRACE(__func__);
124 
128  // transport is shutting down, don't attempt to reconnect
129  return;
130  }
131 
133  BOOST_ASSERT(getState() == TransportState::DOWN);
134 
135  // recreate the socket
136  m_socket = protocol::socket(
137 #if BOOST_VERSION >= 107000
138  m_socket.get_executor()
139 #else
140  m_socket.get_io_service()
141 #endif // BOOST_VERSION >= 107000
142  );
143  this->resetReceiveBuffer();
144  this->resetSendQueue();
145 
146  m_reconnectEvent = getScheduler().schedule(m_nextReconnectWait,
147  [this] { this->handleReconnectTimeout(); });
148  m_socket.async_connect(m_remoteEndpoint, [this] (const auto& e) { this->handleReconnect(e); });
149 }
150 
151 void
152 TcpTransport::handleReconnect(const boost::system::error_code& error)
153 {
157  error == boost::asio::error::operation_aborted) {
158  // transport is shutting down, abort the reconnection attempt and ignore any errors
159  return;
160  }
161 
162  if (error) {
163  NFD_LOG_FACE_TRACE("Reconnection attempt failed: " << error.message());
164  return;
165  }
166 
167  m_reconnectEvent.cancel();
168  m_nextReconnectWait = s_initialReconnectWait;
169 
170  this->setLocalUri(FaceUri(m_socket.local_endpoint()));
171  NFD_LOG_FACE_TRACE("TCP connection reestablished");
173  this->startReceive();
174 }
175 
176 void
177 TcpTransport::handleReconnectTimeout()
178 {
179  // abort the reconnection attempt
180  boost::system::error_code error;
181  m_socket.close(error);
182 
183  // exponentially back off the reconnection timer
184  m_nextReconnectWait =
185  std::min(time::duration_cast<time::milliseconds>(m_nextReconnectWait * s_reconnectWaitMultiplier),
186  s_maxReconnectWait);
187 
188  // do this asynchronously because there could be some callbacks still pending
189  getGlobalIoService().post([this] { reconnect(); });
190 }
191 
192 void
194 {
195  m_reconnectEvent.cancel();
197 }
198 
199 } // namespace face
200 } // namespace nfd
nfd::face::TcpTransport::getSendQueueLength
ssize_t getSendQueueLength() final
Definition: tcp-transport.cpp:61
global.hpp
ndn::detail::ScopedCancelHandle::cancel
void cancel()
Cancel the operation.
Definition: cancel-handle.hpp:109
nfd::face::TransportState::CLOSED
@ CLOSED
the transport is closed, and can be safely deallocated
nfd::face::StreamTransport< boost::asio::ip::tcp >::resetReceiveBuffer
void resetReceiveBuffer()
Definition: stream-transport.hpp:314
nfd::detail::SimulatorIo::post
void post(const std::function< void()> &callback)
Definition: global.cpp:35
nfd::face::MTU_UNLIMITED
const ssize_t MTU_UNLIMITED
indicates the transport has no limit on payload size
Definition: transport.hpp:91
nfd::face::Transport::setMtu
void setMtu(ssize_t mtu)
Definition: transport.hpp:448
nonstd::optional_lite::std11::move
T & move(T &t)
Definition: optional.hpp:421
nfd::face::Transport::setRemoteUri
void setRemoteUri(const FaceUri &uri)
Definition: transport.hpp:406
tcp-transport.hpp
ndn::nfd::LINK_TYPE_POINT_TO_POINT
@ LINK_TYPE_POINT_TO_POINT
link is point-to-point
Definition: nfd-constants.hpp:59
ndn::FaceUri
represents the underlying protocol and address used by a Face
Definition: face-uri.hpp:45
ndn::nfd::FACE_PERSISTENCY_PERMANENT
@ FACE_PERSISTENCY_PERMANENT
face is permanent
Definition: nfd-constants.hpp:49
nfd::face::TcpTransport::canChangePersistencyToImpl
bool canChangePersistencyToImpl(ndn::nfd::FacePersistency newPersistency) const final
invoked by canChangePersistencyTo to perform the check
Definition: tcp-transport.cpp:83
nfd::face::Transport::setScope
void setScope(ndn::nfd::FaceScope scope)
Definition: transport.hpp:418
nfd::face::NFD_LOG_MEMBER_INIT_SPECIALIZED
NFD_LOG_MEMBER_INIT_SPECIALIZED((DatagramTransport< boost::asio::ip::udp, Multicast >), MulticastUdpTransport)
nfd::face::Transport::setState
void setState(TransportState newState)
set transport state
Definition: transport.cpp:173
nfd::face::TransportState::DOWN
@ DOWN
the transport is temporarily down, and is being recovered
NFD_LOG_FACE_DEBUG
#define NFD_LOG_FACE_DEBUG(msg)
Log a message at DEBUG level.
Definition: face-common.hpp:136
nfd::face::StreamTransport< boost::asio::ip::tcp >::getSendQueueBytes
size_t getSendQueueBytes() const
Definition: stream-transport.hpp:330
nfd::face::Transport::getPersistency
ndn::nfd::FacePersistency getPersistency() const
Definition: transport.hpp:424
nfd::getGlobalIoService
detail::SimulatorIo & getGlobalIoService()
Returns the global io_service instance for the calling thread.
Definition: global.cpp:49
ndn::nfd::FacePersistency
FacePersistency
Definition: nfd-constants.hpp:45
nfd::face::TransportState::CLOSING
@ CLOSING
the transport is being closed gracefully, either by the peer or by a call to close()
nfd
Copyright (c) 2011-2015 Regents of the University of California.
Definition: ndn-common.hpp:40
nfd::face::StreamTransport::doClose
void doClose() override
performs Transport specific operations to close the transport
Definition: stream-transport.hpp:136
nfd::face::TcpTransport::afterChangePersistency
void afterChangePersistency(ndn::nfd::FacePersistency oldPersistency) final
invoked after the persistency has been changed
Definition: tcp-transport.cpp:89
nfd::face::StreamTransport::handleError
virtual void handleError(const boost::system::error_code &error)
Definition: stream-transport.hpp:300
NFD_LOG_FACE_TRACE
#define NFD_LOG_FACE_TRACE(msg)
Log a message at TRACE level.
Definition: face-common.hpp:133
nfd::getScheduler
Scheduler & getScheduler()
Returns the global Scheduler instance for the calling thread.
Definition: global.cpp:70
nfd::face::StreamTransport< boost::asio::ip::tcp >
nfd::face::StreamTransport< boost::asio::ip::tcp >::resetSendQueue
void resetSendQueue()
Definition: stream-transport.hpp:321
nfd::face::Transport::setLinkType
void setLinkType(ndn::nfd::LinkType linkType)
Definition: transport.hpp:436
nfd::face::TcpTransport::handleError
void handleError(const boost::system::error_code &error) final
Definition: tcp-transport.cpp:102
nfd::face::TransportState::UP
@ UP
the transport is up and can transmit packets
nfd::face::TcpTransport
A Transport that communicates on a connected TCP socket.
Definition: tcp-transport.hpp:44
nfd::face::StreamTransport< boost::asio::ip::tcp >::m_socket
protocol::socket m_socket
Definition: stream-transport.hpp:98
nfd::face::Transport::setPersistency
void setPersistency(ndn::nfd::FacePersistency newPersistency)
changes face persistency setting
Definition: transport.cpp:150
nfd::face::TransportState::FAILED
@ FAILED
the transport is being closed due to a failure
nfd::face::Transport::getState
TransportState getState() const
Definition: transport.hpp:467
nfd::face::TcpTransport::TcpTransport
TcpTransport(protocol::socket &&socket, ndn::nfd::FacePersistency persistency, ndn::nfd::FaceScope faceScope)
Definition: tcp-transport.cpp:43
nfd::face::TcpTransport::doClose
void doClose() final
performs Transport specific operations to close the transport
Definition: tcp-transport.cpp:193
ndn::nfd::FaceScope
FaceScope
Definition: nfd-constants.hpp:34
NFD_LOG_FACE_WARN
#define NFD_LOG_FACE_WARN(msg)
Log a message at WARN level.
Definition: face-common.hpp:142
nfd::face::StreamTransport< boost::asio::ip::tcp >::startReceive
void startReceive()
Definition: stream-transport.hpp:227
nfd::face::Transport::setLocalUri
void setLocalUri(const FaceUri &uri)
Definition: transport.hpp:394