tcp-channel.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-channel.hpp"
27 #include "face.hpp"
28 #include "generic-link-service.hpp"
29 #include "tcp-transport.hpp"
30 #include "common/global.hpp"
31 
32 #include <boost/asio/ip/v6_only.hpp>
33 
34 namespace nfd::face {
35 
36 NFD_LOG_INIT(TcpChannel);
37 
38 namespace ip = boost::asio::ip;
39 
40 TcpChannel::TcpChannel(const tcp::Endpoint& localEndpoint, bool wantCongestionMarking,
41  DetermineFaceScopeFromAddress determineFaceScope)
42  : m_localEndpoint(localEndpoint)
43  , m_acceptor(getGlobalIoService())
44  , m_socket(getGlobalIoService())
45  , m_wantCongestionMarking(wantCongestionMarking)
46  , m_determineFaceScope(std::move(determineFaceScope))
47 {
48  setUri(FaceUri(m_localEndpoint));
49  NFD_LOG_CHAN_INFO("Creating channel");
50 }
51 
52 void
54  const FaceCreationFailedCallback& onAcceptFailed,
55  int backlog/* = tcp::acceptor::max_connections*/)
56 {
57  if (isListening()) {
58  NFD_LOG_CHAN_WARN("Already listening");
59  return;
60  }
61 
62  m_acceptor.open(m_localEndpoint.protocol());
63  m_acceptor.set_option(ip::tcp::acceptor::reuse_address(true));
64  if (m_localEndpoint.address().is_v6()) {
65  m_acceptor.set_option(ip::v6_only(true));
66  }
67  m_acceptor.bind(m_localEndpoint);
68  m_acceptor.listen(backlog);
69 
70  accept(onFaceCreated, onAcceptFailed);
71  NFD_LOG_CHAN_DEBUG("Started listening");
72 }
73 
74 void
75 TcpChannel::connect(const tcp::Endpoint& remoteEndpoint,
76  const FaceParams& params,
77  const FaceCreatedCallback& onFaceCreated,
78  const FaceCreationFailedCallback& onConnectFailed,
79  time::nanoseconds timeout)
80 {
81  auto it = m_channelFaces.find(remoteEndpoint);
82  if (it != m_channelFaces.end()) {
83  NFD_LOG_CHAN_TRACE("Reusing existing face for " << remoteEndpoint);
84  onFaceCreated(it->second);
85  return;
86  }
87 
88  auto clientSocket = make_shared<ip::tcp::socket>(getGlobalIoService());
89  auto timeoutEvent = getScheduler().schedule(timeout, [=] {
90  handleConnectTimeout(remoteEndpoint, clientSocket, onConnectFailed);
91  });
92 
93  NFD_LOG_CHAN_TRACE("Connecting to " << remoteEndpoint);
94  clientSocket->async_connect(remoteEndpoint, [=] (const auto& e) {
95  this->handleConnect(e, remoteEndpoint, clientSocket, params, timeoutEvent, onFaceCreated, onConnectFailed);
96  });
97 }
98 
99 void
100 TcpChannel::createFace(ip::tcp::socket&& socket,
101  const FaceParams& params,
102  const FaceCreatedCallback& onFaceCreated,
103  const FaceCreationFailedCallback& onFaceCreationFailed)
104 {
105  shared_ptr<Face> face;
106  boost::system::error_code ec;
107  tcp::Endpoint remoteEndpoint = socket.remote_endpoint(ec);
108  if (ec) {
109  NFD_LOG_CHAN_DEBUG("Retrieve socket remote endpoint failed: " << ec.message());
110  if (onFaceCreationFailed) {
111  onFaceCreationFailed(500, "Retrieve socket remote endpoint failed: " + ec.message());
112  }
113  return;
114  }
115 
116  auto it = m_channelFaces.find(remoteEndpoint);
117  if (it == m_channelFaces.end()) {
118  GenericLinkService::Options options;
119  options.allowLocalFields = params.wantLocalFields;
120  options.reliabilityOptions.isEnabled = params.wantLpReliability;
121 
122  if (boost::logic::indeterminate(params.wantCongestionMarking)) {
123  // Use default value for this channel if parameter is indeterminate
124  options.allowCongestionMarking = m_wantCongestionMarking;
125  }
126  else {
127  options.allowCongestionMarking = bool(params.wantCongestionMarking);
128  }
129 
130  if (params.baseCongestionMarkingInterval) {
131  options.baseCongestionMarkingInterval = *params.baseCongestionMarkingInterval;
132  }
133  if (params.defaultCongestionThreshold) {
134  options.defaultCongestionThreshold = *params.defaultCongestionThreshold;
135  }
136 
137  auto linkService = make_unique<GenericLinkService>(options);
138  auto faceScope = m_determineFaceScope(socket.local_endpoint().address(),
139  socket.remote_endpoint().address());
140  auto transport = make_unique<TcpTransport>(std::move(socket), params.persistency, faceScope);
141  face = make_shared<Face>(std::move(linkService), std::move(transport));
142  face->setChannel(weak_from_this());
143 
144  m_channelFaces[remoteEndpoint] = face;
145  connectFaceClosedSignal(*face, [this, remoteEndpoint] { m_channelFaces.erase(remoteEndpoint); });
146  }
147  else {
148  // we already have a face for this endpoint, just reuse it
149  face = it->second;
150  NFD_LOG_CHAN_TRACE("Reusing existing face for " << remoteEndpoint);
151 
152  boost::system::error_code error;
153  socket.shutdown(ip::tcp::socket::shutdown_both, error);
154  socket.close(error);
155  }
156 
157  // Need to invoke the callback regardless of whether or not we have already created
158  // the face so that control responses and such can be sent.
159  onFaceCreated(face);
160 }
161 
162 void
163 TcpChannel::accept(const FaceCreatedCallback& onFaceCreated,
164  const FaceCreationFailedCallback& onAcceptFailed)
165 {
166  m_acceptor.async_accept(m_socket, [=] (const auto& e) { this->handleAccept(e, onFaceCreated, onAcceptFailed); });
167 }
168 
169 void
170 TcpChannel::handleAccept(const boost::system::error_code& error,
171  const FaceCreatedCallback& onFaceCreated,
172  const FaceCreationFailedCallback& onAcceptFailed)
173 {
174  if (error) {
175  if (error != boost::asio::error::operation_aborted) {
176  NFD_LOG_CHAN_DEBUG("Accept failed: " << error.message());
177  if (onAcceptFailed)
178  onAcceptFailed(500, "Accept failed: " + error.message());
179  }
180  return;
181  }
182 
183  NFD_LOG_CHAN_TRACE("Incoming connection from " << m_socket.remote_endpoint());
184 
185  FaceParams params;
186  params.persistency = ndn::nfd::FACE_PERSISTENCY_ON_DEMAND;
187  createFace(std::move(m_socket), params, onFaceCreated, onAcceptFailed);
188 
189  // prepare accepting the next connection
190  accept(onFaceCreated, onAcceptFailed);
191 }
192 
193 void
194 TcpChannel::handleConnect(const boost::system::error_code& error,
195  const tcp::Endpoint& remoteEndpoint,
196  const shared_ptr<ip::tcp::socket>& socket,
197  const FaceParams& params,
198  const scheduler::EventId& connectTimeoutEvent,
199  const FaceCreatedCallback& onFaceCreated,
200  const FaceCreationFailedCallback& onConnectFailed)
201 {
202  connectTimeoutEvent.cancel();
203 
204  if (error) {
205  if (error != boost::asio::error::operation_aborted) {
206  NFD_LOG_CHAN_DEBUG("Connection to " << remoteEndpoint << " failed: " << error.message());
207  if (onConnectFailed)
208  onConnectFailed(504, "Connection failed: " + error.message());
209  }
210  return;
211  }
212 
213  NFD_LOG_CHAN_TRACE("Connected to " << socket->remote_endpoint());
214  createFace(std::move(*socket), params, onFaceCreated, onConnectFailed);
215 }
216 
217 void
218 TcpChannel::handleConnectTimeout(const tcp::Endpoint& remoteEndpoint,
219  const shared_ptr<ip::tcp::socket>& socket,
220  const FaceCreationFailedCallback& onConnectFailed)
221 {
222  NFD_LOG_CHAN_DEBUG("Connection to " << remoteEndpoint << " timed out");
223 
224  // abort the connection attempt
225  boost::system::error_code error;
226  socket->close(error);
227 
228  if (onConnectFailed)
229  onConnectFailed(504, "Connection timed out");
230 }
231 
232 } // namespace nfd::face
void setUri(const FaceUri &uri) noexcept
Definition: channel.cpp:34
void listen(const FaceCreatedCallback &onFaceCreated, const FaceCreationFailedCallback &onAcceptFailed, int backlog=boost::asio::ip::tcp::acceptor::max_connections)
Enable listening on the local endpoint, accept connections, and create faces when remote host makes a...
Definition: tcp-channel.cpp:53
TcpChannel(const tcp::Endpoint &localEndpoint, bool wantCongestionMarking, DetermineFaceScopeFromAddress determineFaceScope)
Create TCP channel for the local endpoint.
Definition: tcp-channel.cpp:40
void connect(const tcp::Endpoint &remoteEndpoint, const FaceParams &params, const FaceCreatedCallback &onFaceCreated, const FaceCreationFailedCallback &onConnectFailed, time::nanoseconds timeout=8_s)
Create a face by establishing a TCP connection to remoteEndpoint.
Definition: tcp-channel.cpp:75
bool isListening() const final
Returns whether the channel is listening.
Definition: tcp-channel.hpp:62
#define NFD_LOG_CHAN_DEBUG(msg)
Log a message at DEBUG level.
Definition: channel-log.hpp:49
#define NFD_LOG_CHAN_INFO(msg)
Log a message at INFO level.
Definition: channel-log.hpp:52
#define NFD_LOG_CHAN_WARN(msg)
Log a message at WARN level.
Definition: channel-log.hpp:55
#define NFD_LOG_CHAN_TRACE(msg)
Log a message at TRACE level.
Definition: channel-log.hpp:46
#define NFD_LOG_INIT(name)
Definition: logger.hpp:31
std::function< void(uint32_t status, const std::string &reason)> FaceCreationFailedCallback
Prototype for the callback that is invoked when a face fails to be created.
Definition: channel.hpp:92
std::function< ndn::nfd::FaceScope(const boost::asio::ip::address &local, const boost::asio::ip::address &remote)> DetermineFaceScopeFromAddress
Definition: tcp-channel.hpp:40
std::function< void(const shared_ptr< Face > &)> FaceCreatedCallback
Prototype for the callback that is invoked when a face is created (in response to an incoming connect...
Definition: channel.hpp:88
void connectFaceClosedSignal(Face &face, std::function< void()> f)
Invokes a callback when a face is closed.
Definition: channel.cpp:46
boost::asio::ip::tcp::endpoint Endpoint
Definition: tcp-channel.hpp:34
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
Parameters used to set Transport properties or LinkService options on a newly created face.
Definition: face-common.hpp:85
std::optional< uint64_t > defaultCongestionThreshold
Definition: face-common.hpp:88
std::optional< time::nanoseconds > baseCongestionMarkingInterval
Definition: face-common.hpp:87
ndn::nfd::FacePersistency persistency
Definition: face-common.hpp:86
boost::logic::tribool wantCongestionMarking
Definition: face-common.hpp:92