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