NS-3 based Named Data Networking (NDN) simulator
ndnSIM 2.5: NDN, CCN, CCNx, content centric networks
API Documentation
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-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-channel.hpp"
27 #include "face.hpp"
28 #include "generic-link-service.hpp"
29 #include "tcp-transport.hpp"
30 #include "common/global.hpp"
31 
32 namespace nfd {
33 namespace face {
34 
36 
37 namespace ip = boost::asio::ip;
38 
39 TcpChannel::TcpChannel(const tcp::Endpoint& localEndpoint, bool wantCongestionMarking,
40  DetermineFaceScopeFromAddress determineFaceScope)
41  : m_localEndpoint(localEndpoint)
42  , m_acceptor(getGlobalIoService())
43  , m_socket(getGlobalIoService())
44  , m_wantCongestionMarking(wantCongestionMarking)
45  , m_determineFaceScope(std::move(determineFaceScope))
46 {
47  setUri(FaceUri(m_localEndpoint));
48  NFD_LOG_CHAN_INFO("Creating channel");
49 }
50 
51 void
53  const FaceCreationFailedCallback& onAcceptFailed,
54  int backlog/* = tcp::acceptor::max_connections*/)
55 {
56  if (isListening()) {
57  NFD_LOG_CHAN_WARN("Already listening");
58  return;
59  }
60 
61  m_acceptor.open(m_localEndpoint.protocol());
62  m_acceptor.set_option(ip::tcp::acceptor::reuse_address(true));
63  if (m_localEndpoint.address().is_v6()) {
64  m_acceptor.set_option(ip::v6_only(true));
65  }
66  m_acceptor.bind(m_localEndpoint);
67  m_acceptor.listen(backlog);
68 
69  accept(onFaceCreated, onAcceptFailed);
70  NFD_LOG_CHAN_DEBUG("Started listening");
71 }
72 
73 void
74 TcpChannel::connect(const tcp::Endpoint& remoteEndpoint,
75  const FaceParams& params,
76  const FaceCreatedCallback& onFaceCreated,
77  const FaceCreationFailedCallback& onConnectFailed,
78  time::nanoseconds timeout)
79 {
80  auto it = m_channelFaces.find(remoteEndpoint);
81  if (it != m_channelFaces.end()) {
82  NFD_LOG_CHAN_TRACE("Reusing existing face for " << remoteEndpoint);
83  onFaceCreated(it->second);
84  return;
85  }
86 
87  auto clientSocket = make_shared<ip::tcp::socket>(getGlobalIoService());
88  auto timeoutEvent = getScheduler().schedule(timeout, [=] {
89  handleConnectTimeout(remoteEndpoint, clientSocket, onConnectFailed);
90  });
91 
92  NFD_LOG_CHAN_TRACE("Connecting to " << remoteEndpoint);
93  clientSocket->async_connect(remoteEndpoint, [=] (const auto& e) {
94  this->handleConnect(e, remoteEndpoint, clientSocket, params, timeoutEvent, onFaceCreated, onConnectFailed);
95  });
96 }
97 
98 void
99 TcpChannel::createFace(ip::tcp::socket&& socket,
100  const FaceParams& params,
101  const FaceCreatedCallback& onFaceCreated)
102 {
103  shared_ptr<Face> face;
104  tcp::Endpoint remoteEndpoint = socket.remote_endpoint();
105 
106  auto it = m_channelFaces.find(remoteEndpoint);
107  if (it == m_channelFaces.end()) {
109  options.allowLocalFields = params.wantLocalFields;
111 
112  if (boost::logic::indeterminate(params.wantCongestionMarking)) {
113  // Use default value for this channel if parameter is indeterminate
114  options.allowCongestionMarking = m_wantCongestionMarking;
115  }
116  else {
117  options.allowCongestionMarking = bool(params.wantCongestionMarking);
118  }
119 
120  if (params.baseCongestionMarkingInterval) {
122  }
123  if (params.defaultCongestionThreshold) {
125  }
126 
127  auto linkService = make_unique<GenericLinkService>(options);
128  auto faceScope = m_determineFaceScope(socket.local_endpoint().address(),
129  socket.remote_endpoint().address());
130  auto transport = make_unique<TcpTransport>(std::move(socket), params.persistency, faceScope);
131  face = make_shared<Face>(std::move(linkService), std::move(transport));
132 
133  m_channelFaces[remoteEndpoint] = face;
134  connectFaceClosedSignal(*face, [this, remoteEndpoint] { m_channelFaces.erase(remoteEndpoint); });
135  }
136  else {
137  // we already have a face for this endpoint, just reuse it
138  face = it->second;
139  NFD_LOG_CHAN_TRACE("Reusing existing face for " << remoteEndpoint);
140 
141  boost::system::error_code error;
142  socket.shutdown(ip::tcp::socket::shutdown_both, error);
143  socket.close(error);
144  }
145 
146  // Need to invoke the callback regardless of whether or not we have already created
147  // the face so that control responses and such can be sent.
148  onFaceCreated(face);
149 }
150 
151 void
152 TcpChannel::accept(const FaceCreatedCallback& onFaceCreated,
153  const FaceCreationFailedCallback& onAcceptFailed)
154 {
155  m_acceptor.async_accept(m_socket, [=] (const auto& e) { this->handleAccept(e, onFaceCreated, onAcceptFailed); });
156 }
157 
158 void
159 TcpChannel::handleAccept(const boost::system::error_code& error,
160  const FaceCreatedCallback& onFaceCreated,
161  const FaceCreationFailedCallback& onAcceptFailed)
162 {
163  if (error) {
164  if (error != boost::asio::error::operation_aborted) {
165  NFD_LOG_CHAN_DEBUG("Accept failed: " << error.message());
166  if (onAcceptFailed)
167  onAcceptFailed(500, "Accept failed: " + error.message());
168  }
169  return;
170  }
171 
172  NFD_LOG_CHAN_TRACE("Incoming connection from " << m_socket.remote_endpoint());
173 
174  FaceParams params;
176  createFace(std::move(m_socket), params, onFaceCreated);
177 
178  // prepare accepting the next connection
179  accept(onFaceCreated, onAcceptFailed);
180 }
181 
182 void
183 TcpChannel::handleConnect(const boost::system::error_code& error,
184  const tcp::Endpoint& remoteEndpoint,
185  const shared_ptr<ip::tcp::socket>& socket,
186  const FaceParams& params,
187  const scheduler::EventId& connectTimeoutEvent,
188  const FaceCreatedCallback& onFaceCreated,
189  const FaceCreationFailedCallback& onConnectFailed)
190 {
191  connectTimeoutEvent.cancel();
192 
193  if (error) {
194  if (error != boost::asio::error::operation_aborted) {
195  NFD_LOG_CHAN_DEBUG("Connection to " << remoteEndpoint << " failed: " << error.message());
196  if (onConnectFailed)
197  onConnectFailed(504, "Connection failed: " + error.message());
198  }
199  return;
200  }
201 
202  NFD_LOG_CHAN_TRACE("Connected to " << socket->remote_endpoint());
203  createFace(std::move(*socket), params, onFaceCreated);
204 }
205 
206 void
207 TcpChannel::handleConnectTimeout(const tcp::Endpoint& remoteEndpoint,
208  const shared_ptr<ip::tcp::socket>& socket,
209  const FaceCreationFailedCallback& onConnectFailed)
210 {
211  NFD_LOG_CHAN_DEBUG("Connection to " << remoteEndpoint << " timed out");
212 
213  // abort the connection attempt
214  boost::system::error_code error;
215  socket->close(error);
216 
217  if (onConnectFailed)
218  onConnectFailed(504, "Connection timed out");
219 }
220 
221 } // namespace face
222 } // namespace nfd
global.hpp
nonstd::optional_lite::std11::move
T & move(T &t)
Definition: optional.hpp:421
nfd::face::FaceParams::wantLpReliability
bool wantLpReliability
Definition: face-common.hpp:79
tcp-transport.hpp
ndn::FaceUri
represents the underlying protocol and address used by a Face
Definition: face-uri.hpp:45
nfd::face::FaceParams::wantLocalFields
bool wantLocalFields
Definition: face-common.hpp:78
nfd::face::GenericLinkService::Options::allowCongestionMarking
bool allowCongestionMarking
enables send queue congestion detection and marking
Definition: generic-link-service.hpp:134
nfd::tcp::Endpoint
boost::asio::ip::tcp::endpoint Endpoint
Definition: tcp-channel.hpp:34
ndn::detail::CancelHandle::cancel
void cancel() const
Cancel the operation.
Definition: cancel-handle.cpp:28
nfd::face::DetermineFaceScopeFromAddress
std::function< ndn::nfd::FaceScope(const boost::asio::ip::address &local, const boost::asio::ip::address &remote)> DetermineFaceScopeFromAddress
Definition: tcp-channel.hpp:40
nfd::face::GenericLinkService::Options::defaultCongestionThreshold
size_t defaultCongestionThreshold
default congestion threshold in bytes
Definition: generic-link-service.hpp:150
NFD_LOG_CHAN_DEBUG
#define NFD_LOG_CHAN_DEBUG(msg)
Log a message at DEBUG level.
Definition: channel-log.hpp:49
nfd::getGlobalIoService
detail::SimulatorIo & getGlobalIoService()
Returns the global io_service instance for the calling thread.
Definition: global.cpp:49
nfd::face::FaceParams::persistency
ndn::nfd::FacePersistency persistency
Definition: face-common.hpp:74
ndn::scheduler::EventId
A handle for a scheduled event.
Definition: scheduler.hpp:59
nfd
Copyright (c) 2011-2015 Regents of the University of California.
Definition: ndn-common.hpp:40
NFD_LOG_CHAN_INFO
#define NFD_LOG_CHAN_INFO(msg)
Log a message at INFO level.
Definition: channel-log.hpp:52
tcp-channel.hpp
nfd::face::GenericLinkService::Options::allowLocalFields
bool allowLocalFields
enables encoding of IncomingFaceId, and decoding of NextHopFaceId and CachePolicy
Definition: generic-link-service.hpp:110
NFD_LOG_CHAN_WARN
#define NFD_LOG_CHAN_WARN(msg)
Log a message at WARN level.
Definition: channel-log.hpp:55
nfd::getScheduler
Scheduler & getScheduler()
Returns the global Scheduler instance for the calling thread.
Definition: global.cpp:70
nfd::face::TcpChannel::listen
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:52
NFD_LOG_CHAN_TRACE
#define NFD_LOG_CHAN_TRACE(msg)
Log a message at TRACE level.
Definition: channel-log.hpp:46
nfd::face::GenericLinkService::Options
Options that control the behavior of GenericLinkService.
Definition: generic-link-service.hpp:101
nfd::face::TcpChannel::TcpChannel
TcpChannel(const tcp::Endpoint &localEndpoint, bool wantCongestionMarking, DetermineFaceScopeFromAddress determineFaceScope)
Create TCP channel for the local endpoint.
Definition: tcp-channel.cpp:39
nfd::face::FaceParams::wantCongestionMarking
boost::logic::tribool wantCongestionMarking
Definition: face-common.hpp:80
nfd::face::TcpChannel::isListening
bool isListening() const override
Returns whether the channel is listening.
Definition: tcp-channel.hpp:62
nfd::face::connectFaceClosedSignal
void connectFaceClosedSignal(Face &face, std::function< void()> f)
Invokes a callback when a face is closed.
Definition: channel.cpp:41
nfd::face::FaceParams::baseCongestionMarkingInterval
optional< time::nanoseconds > baseCongestionMarkingInterval
Definition: face-common.hpp:75
nfd::face::FaceCreatedCallback
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:74
ndn::nfd::FACE_PERSISTENCY_ON_DEMAND
@ FACE_PERSISTENCY_ON_DEMAND
face is on-demand
Definition: nfd-constants.hpp:48
nfd::face::GenericLinkService::Options::reliabilityOptions
LpReliability::Options reliabilityOptions
options for reliability
Definition: generic-link-service.hpp:130
nfd::face::GenericLinkService::Options::baseCongestionMarkingInterval
time::nanoseconds baseCongestionMarkingInterval
starting value for congestion marking interval
Definition: generic-link-service.hpp:142
face.hpp
nfd::face::LpReliability::Options::isEnabled
bool isEnabled
enables link-layer reliability
Definition: lp-reliability.hpp:52
nfd::face::FaceParams
Parameters used to set Transport properties or LinkService options on a newly created face.
Definition: face-common.hpp:73
nfd::face::TcpChannel
Class implementing TCP-based channel to create faces.
Definition: tcp-channel.hpp:50
nfd::face::Channel::setUri
void setUri(const FaceUri &uri)
Definition: channel.cpp:35
nfd::face::FaceCreationFailedCallback
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:78
nfd::face::TcpChannel::connect
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:74
NFD_LOG_INIT
#define NFD_LOG_INIT(name)
Definition: logger.hpp:31
nfd::face::FaceParams::defaultCongestionThreshold
optional< uint64_t > defaultCongestionThreshold
Definition: face-common.hpp:76