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