NFD: Named Data Networking Forwarding Daemon 24.07-28-gdcc0e6e0
Loading...
Searching...
No Matches
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-2023, 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#include <boost/asio/defer.hpp>
30
31#if defined(__linux__)
32#include <linux/sockios.h>
33#include <sys/ioctl.h>
34#endif
35
36namespace nfd::face {
37
38namespace ip = boost::asio::ip;
39
40NFD_LOG_MEMBER_INIT_SPECIALIZED(StreamTransport<ip::tcp>, TcpTransport);
41
42TcpTransport::TcpTransport(ip::tcp::socket&& socket,
43 ndn::nfd::FacePersistency persistency,
44 ndn::nfd::FaceScope faceScope)
45 : StreamTransport(std::move(socket))
46 , m_remoteEndpoint(m_socket.remote_endpoint())
47 , m_nextReconnectWait(INITIAL_RECONNECT_DELAY)
48{
49 this->setLocalUri(FaceUri(m_socket.local_endpoint()));
50 this->setRemoteUri(FaceUri(m_socket.remote_endpoint()));
51 this->setScope(faceScope);
52 this->setPersistency(persistency);
53 this->setLinkType(ndn::nfd::LINK_TYPE_POINT_TO_POINT);
54 this->setMtu(MTU_UNLIMITED);
55
56 NFD_LOG_FACE_DEBUG("Creating transport");
57}
58
59ssize_t
61{
62 int queueLength = getSendQueueBytes();
63
64 // We want to obtain the amount of "not sent" bytes instead of the amount of "not sent" + "not
65 // acked" bytes. On Linux, we use SIOCOUTQNSD for this reason. However, macOS does not provide an
66 // efficient mechanism to obtain this value (SO_NWRITE includes both "not sent" and "not acked").
67#if defined(__linux__)
68 int nsd;
69 if (ioctl(m_socket.native_handle(), SIOCOUTQNSD, &nsd) < 0) {
70 NFD_LOG_FACE_WARN("Failed to obtain send queue length from socket: " << std::strerror(errno));
71 }
72 else if (nsd > 0) {
73 NFD_LOG_FACE_TRACE("SIOCOUTQNSD=" << nsd);
74 queueLength += nsd;
75 }
76#endif
77
78 return queueLength;
79}
80
81bool
82TcpTransport::canChangePersistencyToImpl(ndn::nfd::FacePersistency newPersistency) const
83{
84 return true;
85}
86
87void
88TcpTransport::afterChangePersistency(ndn::nfd::FacePersistency oldPersistency)
89{
90 // if persistency was changed from permanent to any other value
91 if (oldPersistency == ndn::nfd::FACE_PERSISTENCY_PERMANENT) {
92 if (this->getState() == TransportState::DOWN) {
93 // non-permanent transport cannot be in DOWN state, so fail hard
95 doClose();
96 }
97 }
98}
99
100void
101TcpTransport::handleError(const boost::system::error_code& error)
102{
103 if (this->getPersistency() == ndn::nfd::FACE_PERSISTENCY_PERMANENT) {
104 NFD_LOG_FACE_TRACE("TCP socket error: " << error.message());
106
107 // cancel all outstanding operations
108 boost::system::error_code ec;
109 m_socket.cancel(ec);
110
111 // do this asynchronously because there could be some callbacks still pending
112 boost::asio::defer(getGlobalIoService(), [this] { reconnect(); });
113 }
114 else {
116 }
117}
118
119void
120TcpTransport::reconnect()
121{
122 NFD_LOG_FACE_TRACE(__func__);
123
127 // transport is shutting down, don't attempt to reconnect
128 return;
129 }
130
131 BOOST_ASSERT(getPersistency() == ndn::nfd::FACE_PERSISTENCY_PERMANENT);
132 BOOST_ASSERT(getState() == TransportState::DOWN);
133
134 // recreate the socket
135 m_socket = ip::tcp::socket(m_socket.get_executor());
136 this->resetReceiveBuffer();
137 this->resetSendQueue();
138
139 m_reconnectEvent = getScheduler().schedule(m_nextReconnectWait,
140 [this] { this->handleReconnectTimeout(); });
141 m_socket.async_connect(m_remoteEndpoint, [this] (const auto& e) { this->handleReconnect(e); });
142}
143
144void
145TcpTransport::handleReconnect(const boost::system::error_code& error)
146{
150 error == boost::asio::error::operation_aborted) {
151 // transport is shutting down, abort the reconnection attempt and ignore any errors
152 return;
153 }
154
155 if (error) {
156 NFD_LOG_FACE_TRACE("Reconnection attempt failed: " << error.message());
157 return;
158 }
159
160 m_reconnectEvent.cancel();
161 m_nextReconnectWait = INITIAL_RECONNECT_DELAY;
162
163 this->setLocalUri(FaceUri(m_socket.local_endpoint()));
164 NFD_LOG_FACE_TRACE("TCP connection reestablished");
166 this->startReceive();
167}
168
169void
170TcpTransport::handleReconnectTimeout()
171{
172 // abort the reconnection attempt
173 boost::system::error_code error;
174 m_socket.close(error);
175
176 // exponentially back off the reconnection timer
177 m_nextReconnectWait =
178 std::min(time::duration_cast<time::milliseconds>(m_nextReconnectWait * RECONNECT_DELAY_MULTIPLIER),
179 MAX_RECONNECT_DELAY);
180
181 // do this asynchronously because there could be some callbacks still pending
182 boost::asio::defer(getGlobalIoService(), [this] { reconnect(); });
183}
184
185void
187{
188 m_reconnectEvent.cancel();
190}
191
192} // namespace nfd::face
Implements a 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.
void handleError(const boost::system::error_code &error) final
void afterChangePersistency(ndn::nfd::FacePersistency oldPersistency) final
Invoked after the persistency has been changed.
TcpTransport(boost::asio::ip::tcp::socket &&socket, ndn::nfd::FacePersistency persistency, ndn::nfd::FaceScope faceScope)
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
void setPersistency(ndn::nfd::FacePersistency newPersistency)
Changes the persistency setting of the transport.
ndn::nfd::FacePersistency getPersistency() const noexcept
Returns the current persistency setting of the transport.
void setMtu(ssize_t mtu) noexcept
TransportState getState() const noexcept
Returns the current transport state.
void setState(TransportState newState)
Set transport state.
void setLocalUri(const FaceUri &uri) noexcept
void setLinkType(ndn::nfd::LinkType linkType) noexcept
void setRemoteUri(const FaceUri &uri) noexcept
#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.
ndn::Scheduler & getScheduler()
Returns the global Scheduler instance for the calling thread.
Definition global.cpp:45
boost::asio::io_context & getGlobalIoService()
Returns the global io_context instance for the calling thread.
Definition global.cpp:36