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 
34 NFD_LOG_INIT("TcpChannel");
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>(ref(getGlobalIoService()));
87  auto timeoutEvent = scheduler::schedule(timeout, bind(&TcpChannel::handleConnectTimeout, this,
88  remoteEndpoint, clientSocket, onConnectFailed));
89 
90  NFD_LOG_CHAN_TRACE("Connecting to " << remoteEndpoint);
91  clientSocket->async_connect(remoteEndpoint,
92  bind(&TcpChannel::handleConnect, this,
93  boost::asio::placeholders::error, remoteEndpoint, clientSocket,
94  params, timeoutEvent, onFaceCreated, onConnectFailed));
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, bind(&TcpChannel::handleAccept, this,
155  boost::asio::placeholders::error,
156  onFaceCreated, onAcceptFailed));
157 }
158 
159 void
160 TcpChannel::handleAccept(const boost::system::error_code& error,
161  const FaceCreatedCallback& onFaceCreated,
162  const FaceCreationFailedCallback& onAcceptFailed)
163 {
164  if (error) {
165  if (error != boost::asio::error::operation_aborted) {
166  NFD_LOG_CHAN_DEBUG("Accept failed: " << error.message());
167  if (onAcceptFailed)
168  onAcceptFailed(500, "Accept failed: " + error.message());
169  }
170  return;
171  }
172 
173  NFD_LOG_CHAN_TRACE("Incoming connection from " << m_socket.remote_endpoint());
174 
175  FaceParams params;
177  createFace(std::move(m_socket), params, onFaceCreated);
178 
179  // prepare accepting the next connection
180  accept(onFaceCreated, onAcceptFailed);
181 }
182 
183 void
184 TcpChannel::handleConnect(const boost::system::error_code& error,
185  const tcp::Endpoint& remoteEndpoint,
186  const shared_ptr<ip::tcp::socket>& socket,
187  const FaceParams& params,
188  const scheduler::EventId& connectTimeoutEvent,
189  const FaceCreatedCallback& onFaceCreated,
190  const FaceCreationFailedCallback& onConnectFailed)
191 {
192  scheduler::cancel(connectTimeoutEvent);
193 
194 #if (BOOST_VERSION == 105400)
195  // To handle regression in Boost 1.54
196  // https://svn.boost.org/trac/boost/ticket/8795
197  boost::system::error_code anotherErrorCode;
198  socket->remote_endpoint(anotherErrorCode);
199  if (error || anotherErrorCode) {
200 #else
201  if (error) {
202 #endif
203  if (error != boost::asio::error::operation_aborted) {
204  NFD_LOG_CHAN_DEBUG("Connection to " << remoteEndpoint << " failed: " << error.message());
205  if (onConnectFailed)
206  onConnectFailed(504, "Connection failed: " + error.message());
207  }
208  return;
209  }
210 
211  NFD_LOG_CHAN_TRACE("Connected to " << socket->remote_endpoint());
212  createFace(std::move(*socket), params, onFaceCreated);
213 }
214 
215 void
216 TcpChannel::handleConnectTimeout(const tcp::Endpoint& remoteEndpoint,
217  const shared_ptr<ip::tcp::socket>& socket,
218  const FaceCreationFailedCallback& onConnectFailed)
219 {
220  NFD_LOG_CHAN_DEBUG("Connection to " << remoteEndpoint << " timed out");
221 
222  // abort the connection attempt
223  boost::system::error_code error;
224  socket->close(error);
225 
226  if (onConnectFailed)
227  onConnectFailed(504, "Connection timed out");
228 }
229 
230 } // namespace face
231 } // namespace nfd
optional< time::nanoseconds > baseCongestionMarkingInterval
Definition: channel.hpp:101
void setUri(const FaceUri &uri)
Definition: channel.cpp:34
bool isListening() const override
Returns whether the channel is listening.
Definition: tcp-channel.hpp:63
bool allowLocalFields
enables encoding of IncomingFaceId, and decoding of NextHopFaceId and CachePolicy ...
void cancel(const EventId &eventId)
Cancel a scheduled event.
Definition: scheduler.cpp:54
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
STL namespace.
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
optional< uint64_t > defaultCongestionThreshold
Definition: channel.hpp:102
std::shared_ptr< ns3::EventId > EventId
Definition: scheduler.hpp:51
#define NFD_LOG_CHAN_DEBUG(msg)
Log a message at DEBUG level.
Definition: channel-log.hpp:49
Parameters used to set Transport properties or LinkService options on a newly created face...
Definition: channel.hpp:87
TcpChannel(const tcp::Endpoint &localEndpoint, bool wantCongestionMarking, DetermineFaceScopeFromAddress determineFaceScope)
Create TCP channel for the local endpoint.
Definition: tcp-channel.cpp:38
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
ndn::nfd::FacePersistency persistency
Definition: channel.hpp:100
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
boost::logic::tribool wantCongestionMarking
Definition: channel.hpp:105
EventId schedule(time::nanoseconds after, const EventCallback &event)
Schedule an event.
Definition: scheduler.cpp:48
#define NFD_LOG_INIT(name)
Definition: logger.hpp:34