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-2022, 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::face {
35 
36 NFD_LOG_MEMBER_INIT_SPECIALIZED(StreamTransport<boost::asio::ip::tcp>, TcpTransport);
37 
38 TcpTransport::TcpTransport(protocol::socket&& socket,
39  ndn::nfd::FacePersistency persistency,
40  ndn::nfd::FaceScope faceScope)
41  : StreamTransport(std::move(socket))
42  , m_remoteEndpoint(m_socket.remote_endpoint())
43  , m_nextReconnectWait(INITIAL_RECONNECT_DELAY)
44 {
45  this->setLocalUri(FaceUri(m_socket.local_endpoint()));
46  this->setRemoteUri(FaceUri(m_socket.remote_endpoint()));
47  this->setScope(faceScope);
48  this->setPersistency(persistency);
49  this->setLinkType(ndn::nfd::LINK_TYPE_POINT_TO_POINT);
50  this->setMtu(MTU_UNLIMITED);
51 
52  NFD_LOG_FACE_DEBUG("Creating transport");
53 }
54 
55 ssize_t
57 {
58  int queueLength = getSendQueueBytes();
59 
60  // We want to obtain the amount of "not sent" bytes instead of the amount of "not sent" + "not
61  // acked" bytes. On Linux, we use SIOCOUTQNSD for this reason. However, macOS does not provide an
62  // efficient mechanism to obtain this value (SO_NWRITE includes both "not sent" and "not acked").
63 #if defined(__linux__)
64  int nsd;
65  if (ioctl(m_socket.native_handle(), SIOCOUTQNSD, &nsd) < 0) {
66  NFD_LOG_FACE_WARN("Failed to obtain send queue length from socket: " << std::strerror(errno));
67  }
68  else if (nsd > 0) {
69  NFD_LOG_FACE_TRACE("SIOCOUTQNSD=" << nsd);
70  queueLength += nsd;
71  }
72 #endif
73 
74  return queueLength;
75 }
76 
77 bool
78 TcpTransport::canChangePersistencyToImpl(ndn::nfd::FacePersistency newPersistency) const
79 {
80  return true;
81 }
82 
83 void
84 TcpTransport::afterChangePersistency(ndn::nfd::FacePersistency oldPersistency)
85 {
86  // if persistency was changed from permanent to any other value
87  if (oldPersistency == ndn::nfd::FACE_PERSISTENCY_PERMANENT) {
88  if (this->getState() == TransportState::DOWN) {
89  // non-permanent transport cannot be in DOWN state, so fail hard
91  doClose();
92  }
93  }
94 }
95 
96 void
97 TcpTransport::handleError(const boost::system::error_code& error)
98 {
99  if (this->getPersistency() == ndn::nfd::FACE_PERSISTENCY_PERMANENT) {
100  NFD_LOG_FACE_TRACE("TCP socket error: " << error.message());
102 
103  // cancel all outstanding operations
104  boost::system::error_code ec;
105  m_socket.cancel(ec);
106 
107  // do this asynchronously because there could be some callbacks still pending
108  getGlobalIoService().post([this] { reconnect(); });
109  }
110  else {
112  }
113 }
114 
115 void
116 TcpTransport::reconnect()
117 {
118  NFD_LOG_FACE_TRACE(__func__);
119 
123  // transport is shutting down, don't attempt to reconnect
124  return;
125  }
126 
127  BOOST_ASSERT(getPersistency() == ndn::nfd::FACE_PERSISTENCY_PERMANENT);
128  BOOST_ASSERT(getState() == TransportState::DOWN);
129 
130  // recreate the socket
131  m_socket = protocol::socket(
132 #if BOOST_VERSION >= 107000
133  m_socket.get_executor()
134 #else
135  m_socket.get_io_service()
136 #endif // BOOST_VERSION >= 107000
137  );
138  this->resetReceiveBuffer();
139  this->resetSendQueue();
140 
141  m_reconnectEvent = getScheduler().schedule(m_nextReconnectWait,
142  [this] { this->handleReconnectTimeout(); });
143  m_socket.async_connect(m_remoteEndpoint, [this] (const auto& e) { this->handleReconnect(e); });
144 }
145 
146 void
147 TcpTransport::handleReconnect(const boost::system::error_code& error)
148 {
152  error == boost::asio::error::operation_aborted) {
153  // transport is shutting down, abort the reconnection attempt and ignore any errors
154  return;
155  }
156 
157  if (error) {
158  NFD_LOG_FACE_TRACE("Reconnection attempt failed: " << error.message());
159  return;
160  }
161 
162  m_reconnectEvent.cancel();
163  m_nextReconnectWait = INITIAL_RECONNECT_DELAY;
164 
165  this->setLocalUri(FaceUri(m_socket.local_endpoint()));
166  NFD_LOG_FACE_TRACE("TCP connection reestablished");
168  this->startReceive();
169 }
170 
171 void
172 TcpTransport::handleReconnectTimeout()
173 {
174  // abort the reconnection attempt
175  boost::system::error_code error;
176  m_socket.close(error);
177 
178  // exponentially back off the reconnection timer
179  m_nextReconnectWait =
180  std::min(time::duration_cast<time::milliseconds>(m_nextReconnectWait * RECONNECT_DELAY_MULTIPLIER),
181  MAX_RECONNECT_DELAY);
182 
183  // do this asynchronously because there could be some callbacks still pending
184  getGlobalIoService().post([this] { reconnect(); });
185 }
186 
187 void
189 {
190  m_reconnectEvent.cancel();
192 }
193 
194 } // namespace nfd::face
Implements Transport for stream-based protocols.
virtual void handleError(const boost::system::error_code &error)
void doClose() override
Performs Transport specific operations to close the transport.
bool canChangePersistencyToImpl(ndn::nfd::FacePersistency newPersistency) const final
Invoked by canChangePersistencyTo to perform the check.
TcpTransport(protocol::socket &&socket, ndn::nfd::FacePersistency persistency, ndn::nfd::FaceScope faceScope)
void handleError(const boost::system::error_code &error) final
void afterChangePersistency(ndn::nfd::FacePersistency oldPersistency) final
Invoked after the persistency has been changed.
ssize_t getSendQueueLength() final
Returns the current send queue length of the transport (in octets).
void doClose() final
Performs Transport specific operations to close the transport.
void setScope(ndn::nfd::FaceScope scope) noexcept
Definition: transport.hpp:346
void setPersistency(ndn::nfd::FacePersistency newPersistency)
Changes the persistency setting of the transport.
Definition: transport.cpp:152
ndn::nfd::FacePersistency getPersistency() const noexcept
Returns the current persistency setting of the transport.
Definition: transport.hpp:227
void setMtu(ssize_t mtu) noexcept
Definition: transport.cpp:114
TransportState getState() const noexcept
Returns the current transport state.
Definition: transport.hpp:291
void setState(TransportState newState)
Set transport state.
Definition: transport.cpp:175
void setLocalUri(const FaceUri &uri) noexcept
Definition: transport.hpp:334
void setLinkType(ndn::nfd::LinkType linkType) noexcept
Definition: transport.hpp:352
void setRemoteUri(const FaceUri &uri) noexcept
Definition: transport.hpp:340
#define NFD_LOG_FACE_DEBUG(msg)
Log a message at DEBUG level.
#define NFD_LOG_FACE_WARN(msg)
Log a message at WARN level.
#define NFD_LOG_FACE_TRACE(msg)
Log a message at TRACE level.
#define NFD_LOG_MEMBER_INIT_SPECIALIZED(cls, name)
Definition: logger.hpp:35
@ CLOSED
the transport is closed, and can be safely deallocated
@ CLOSING
the transport is being closed gracefully, either by the peer or by a call to close()
@ FAILED
the transport is being closed due to a failure
@ DOWN
the transport is temporarily down, and is being recovered
@ UP
the transport is up and can transmit packets
constexpr ssize_t MTU_UNLIMITED
Indicates that the transport has no limit on payload size.
Definition: transport.hpp:92
boost::asio::io_service & getGlobalIoService()
Returns the global io_service instance for the calling thread.
Definition: global.cpp:36
Scheduler & getScheduler()
Returns the global Scheduler instance for the calling thread.
Definition: global.cpp:45