NS-3 based Named Data Networking (NDN) simulator
ndnSIM 2.3: 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-2017, 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 
39  : m_localEndpoint(localEndpoint)
40  , m_acceptor(getGlobalIoService())
41  , m_socket(getGlobalIoService())
42 {
43  setUri(FaceUri(m_localEndpoint));
44  NFD_LOG_CHAN_INFO("Creating channel");
45 }
46 
47 void
49  const FaceCreationFailedCallback& onAcceptFailed,
50  int backlog/* = tcp::acceptor::max_connections*/)
51 {
52  if (isListening()) {
53  NFD_LOG_CHAN_WARN("Already listening");
54  return;
55  }
56 
57  m_acceptor.open(m_localEndpoint.protocol());
58  m_acceptor.set_option(ip::tcp::acceptor::reuse_address(true));
59  if (m_localEndpoint.address().is_v6()) {
60  m_acceptor.set_option(ip::v6_only(true));
61  }
62  m_acceptor.bind(m_localEndpoint);
63  m_acceptor.listen(backlog);
64 
65  accept(onFaceCreated, onAcceptFailed);
66  NFD_LOG_CHAN_DEBUG("Started listening");
67 }
68 
69 void
70 TcpChannel::connect(const tcp::Endpoint& remoteEndpoint,
71  ndn::nfd::FacePersistency persistency,
72  bool wantLocalFields,
73  bool wantLpReliability,
74  const FaceCreatedCallback& onFaceCreated,
75  const FaceCreationFailedCallback& onConnectFailed,
76  time::nanoseconds timeout)
77 {
78  auto it = m_channelFaces.find(remoteEndpoint);
79  if (it != m_channelFaces.end()) {
80  NFD_LOG_CHAN_TRACE("Reusing existing face for " << remoteEndpoint);
81  onFaceCreated(it->second);
82  return;
83  }
84 
85  auto clientSocket = make_shared<ip::tcp::socket>(ref(getGlobalIoService()));
86  auto timeoutEvent = scheduler::schedule(timeout, bind(&TcpChannel::handleConnectTimeout, this,
87  remoteEndpoint, clientSocket, onConnectFailed));
88 
89  NFD_LOG_CHAN_TRACE("Connecting to " << remoteEndpoint);
90  clientSocket->async_connect(remoteEndpoint,
91  bind(&TcpChannel::handleConnect, this,
92  boost::asio::placeholders::error, remoteEndpoint, clientSocket,
93  // Creating a parameters struct works around limit on number of
94  // parameters to bind
95  ConnectParams{persistency, wantLocalFields, wantLpReliability},
96  timeoutEvent, onFaceCreated, onConnectFailed));
97 }
98 
99 void
100 TcpChannel::createFace(ip::tcp::socket&& socket,
101  ndn::nfd::FacePersistency persistency,
102  bool wantLocalFields,
103  bool wantLpReliability,
104  const FaceCreatedCallback& onFaceCreated)
105 {
106  shared_ptr<Face> face;
107  tcp::Endpoint remoteEndpoint = socket.remote_endpoint();
108 
109  auto it = m_channelFaces.find(remoteEndpoint);
110  if (it == m_channelFaces.end()) {
112  options.allowLocalFields = wantLocalFields;
113  options.reliabilityOptions.isEnabled = wantLpReliability;
114  auto linkService = make_unique<GenericLinkService>(options);
115 
116  auto transport = make_unique<TcpTransport>(std::move(socket), persistency);
117  face = make_shared<Face>(std::move(linkService), std::move(transport));
118 
119  m_channelFaces[remoteEndpoint] = face;
120  connectFaceClosedSignal(*face, [this, remoteEndpoint] { m_channelFaces.erase(remoteEndpoint); });
121  }
122  else {
123  // we already have a face for this endpoint, just reuse it
124  face = it->second;
125  NFD_LOG_CHAN_TRACE("Reusing existing face for " << remoteEndpoint);
126 
127  boost::system::error_code error;
128  socket.shutdown(ip::tcp::socket::shutdown_both, error);
129  socket.close(error);
130  }
131 
132  // Need to invoke the callback regardless of whether or not we have already created
133  // the face so that control responses and such can be sent.
134  onFaceCreated(face);
135 }
136 
137 void
138 TcpChannel::accept(const FaceCreatedCallback& onFaceCreated,
139  const FaceCreationFailedCallback& onAcceptFailed)
140 {
141  m_acceptor.async_accept(m_socket, bind(&TcpChannel::handleAccept, this,
142  boost::asio::placeholders::error,
143  onFaceCreated, onAcceptFailed));
144 }
145 
146 void
147 TcpChannel::handleAccept(const boost::system::error_code& error,
148  const FaceCreatedCallback& onFaceCreated,
149  const FaceCreationFailedCallback& onAcceptFailed)
150 {
151  if (error) {
153  NFD_LOG_CHAN_DEBUG("Accept failed: " << error.message());
154  if (onAcceptFailed)
155  onAcceptFailed(500, "Accept failed: " + error.message());
156  }
157  return;
158  }
159 
160  NFD_LOG_CHAN_TRACE("Incoming connection from " << m_socket.remote_endpoint());
161  createFace(std::move(m_socket), ndn::nfd::FACE_PERSISTENCY_ON_DEMAND, false, false, onFaceCreated);
162 
163  // prepare accepting the next connection
164  accept(onFaceCreated, onAcceptFailed);
165 }
166 
167 void
168 TcpChannel::handleConnect(const boost::system::error_code& error,
169  const tcp::Endpoint& remoteEndpoint,
170  const shared_ptr<ip::tcp::socket>& socket,
171  TcpChannel::ConnectParams params,
172  const scheduler::EventId& connectTimeoutEvent,
173  const FaceCreatedCallback& onFaceCreated,
174  const FaceCreationFailedCallback& onConnectFailed)
175 {
176  scheduler::cancel(connectTimeoutEvent);
177 
178 #if (BOOST_VERSION == 105400)
179  // To handle regression in Boost 1.54
180  // https://svn.boost.org/trac/boost/ticket/8795
181  boost::system::error_code anotherErrorCode;
182  socket->remote_endpoint(anotherErrorCode);
183  if (error || anotherErrorCode) {
184 #else
185  if (error) {
186 #endif
188  NFD_LOG_CHAN_DEBUG("Connection to " << remoteEndpoint << " failed: " << error.message());
189  if (onConnectFailed)
190  onConnectFailed(504, "Connection failed: " + error.message());
191  }
192  return;
193  }
194 
195  NFD_LOG_CHAN_TRACE("Connected to " << socket->remote_endpoint());
196  createFace(std::move(*socket), params.persistency, params.wantLocalFields,
197  params.wantLpReliability, onFaceCreated);
198 }
199 
200 void
201 TcpChannel::handleConnectTimeout(const tcp::Endpoint& remoteEndpoint,
202  const shared_ptr<ip::tcp::socket>& socket,
203  const FaceCreationFailedCallback& onConnectFailed)
204 {
205  NFD_LOG_CHAN_DEBUG("Connection to " << remoteEndpoint << " timed out");
206 
207  // abort the connection attempt
208  boost::system::error_code error;
209  socket->close(error);
210 
211  if (onConnectFailed)
212  onConnectFailed(504, "Connection timed out");
213 }
214 
215 } // namespace face
216 } // namespace nfd
void setUri(const FaceUri &uri)
Definition: channel.cpp:34
TcpChannel(const tcp::Endpoint &localEndpoint)
Create TCP channel for the local endpoint.
Definition: tcp-channel.cpp:38
bool isListening() const override
Returns whether the channel is listening.
Definition: tcp-channel.hpp:60
void connect(const tcp::Endpoint &remoteEndpoint, ndn::nfd::FacePersistency persistency, bool wantLocalFields, bool wantLpReliability, const FaceCreatedCallback &onFaceCreated, const FaceCreationFailedCallback &onConnectFailed, time::nanoseconds timeout=time::seconds(4))
Create a face by establishing a TCP connection to remoteEndpoint.
Definition: tcp-channel.cpp:70
Accept any value the remote endpoint offers.
Definition: enabled.hpp:194
bool allowLocalFields
enables encoding of IncomingFaceId, and decoding of NextHopFaceId and CachePolicy ...
void cancel(const EventId &eventId)
cancel a scheduled event
Definition: scheduler.cpp:53
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:48
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:48
#define NFD_LOG_CHAN_DEBUG(msg)
Log a message at DEBUG level.
Definition: channel-log.hpp:49
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
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:43
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
Options that control the behavior of GenericLinkService.
EventId schedule(time::nanoseconds after, const EventCallback &event)
schedule an event
Definition: scheduler.cpp:47
Catch-all error for socket component errors that don&#39;t fit in other categories.
Definition: base.hpp:83
#define NFD_LOG_INIT(name)
Definition: logger.hpp:34
function< void(const shared_ptr< Face > &newFace)> FaceCreatedCallback
Prototype for the callback that is invoked when a face is created (in response to an incoming connect...
Definition: channel.hpp:35