NS-3 based Named Data Networking (NDN) simulator
ndnSIM 2.5: NDN, CCN, CCNx, content centric networks
API Documentation
websocket-transport.cpp
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * Copyright (c) 2014-2022, 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 "websocket-transport.hpp"
27 #include "common/global.hpp"
28 
29 namespace nfd {
30 namespace face {
31 
33 
34 static bool
35 isLoopback(const boost::asio::ip::address& addr)
36 {
37  if (addr.is_loopback()) {
38  return true;
39  }
40  // Workaround for loopback IPv4-mapped IPv6 addresses
41  // see https://svn.boost.org/trac/boost/ticket/9084
42  else if (addr.is_v6()) {
43  auto addr6 = addr.to_v6();
44  if (addr6.is_v4_mapped()) {
45  return addr6.to_v4().is_loopback();
46  }
47  }
48 
49  return false;
50 }
51 
54  time::milliseconds pingInterval)
55  : m_handle(hdl)
56  , m_server(server)
57  , m_pingInterval(pingInterval)
58 {
59  const auto& sock = m_server.get_con_from_hdl(hdl)->get_socket();
60  this->setLocalUri(FaceUri(sock.local_endpoint(), "ws"));
61  this->setRemoteUri(FaceUri(sock.remote_endpoint(), "wsclient"));
62 
63  if (isLoopback(sock.local_endpoint().address()) &&
64  isLoopback(sock.remote_endpoint().address())) {
66  }
67  else {
69  }
70 
73  this->setMtu(MTU_UNLIMITED);
74 
75  this->schedulePing();
76 
77  NFD_LOG_FACE_DEBUG("Creating transport");
78 }
79 
80 void
81 WebSocketTransport::doSend(const Block& packet)
82 {
83  NFD_LOG_FACE_TRACE(__func__);
84 
85  websocketpp::lib::error_code error;
86  m_server.send(m_handle, packet.wire(), packet.size(),
88  if (error)
89  return processErrorCode(error);
90 
91  NFD_LOG_FACE_TRACE("Successfully sent: " << packet.size() << " bytes");
92 }
93 
94 void
95 WebSocketTransport::receiveMessage(const std::string& msg)
96 {
97  NFD_LOG_FACE_TRACE("Received: " << msg.size() << " bytes");
98 
99  bool isOk = false;
100  Block element;
101  std::tie(isOk, element) = Block::fromBuffer({reinterpret_cast<const uint8_t*>(msg.data()), msg.size()});
102  if (!isOk) {
103  NFD_LOG_FACE_WARN("Failed to parse message payload");
104  return;
105  }
106 
107  this->receive(element);
108 }
109 
110 void
111 WebSocketTransport::schedulePing()
112 {
113  m_pingEventId = getScheduler().schedule(m_pingInterval, [this] { sendPing(); });
114 }
115 
116 void
117 WebSocketTransport::sendPing()
118 {
119  NFD_LOG_FACE_TRACE(__func__);
120 
121  websocketpp::lib::error_code error;
122  m_server.ping(m_handle, "NFD-WebSocket", error);
123  if (error)
124  return processErrorCode(error);
125 
126  ++this->nOutPings;
127 
128  this->schedulePing();
129 }
130 
131 void
133 {
134  NFD_LOG_FACE_TRACE(__func__);
135 
136  ++this->nInPongs;
137 }
138 
139 void
141 {
142  NFD_LOG_FACE_ERROR("Pong timeout");
144  doClose();
145 }
146 
147 void
148 WebSocketTransport::processErrorCode(const websocketpp::lib::error_code& error)
149 {
150  NFD_LOG_FACE_TRACE(__func__);
151 
155  // transport is shutting down, ignore any errors
156  return;
157 
158  NFD_LOG_FACE_ERROR("Send or ping operation failed: " << error.message());
160  doClose();
161 }
162 
163 void
165 {
166  NFD_LOG_FACE_TRACE(__func__);
167 
168  m_pingEventId.cancel();
169 
170  // use the non-throwing variant and ignore errors, if any
171  websocketpp::lib::error_code error;
172  m_server.close(m_handle, websocketpp::close::status::normal, "closed by NFD", error);
173 
175 }
176 
177 } // namespace face
178 } // namespace nfd
void setPersistency(ndn::nfd::FacePersistency newPersistency)
changes face persistency setting
Definition: transport.cpp:164
static NDN_CXX_NODISCARD std::tuple< bool, Block > fromBuffer(ConstBufferPtr buffer, size_t offset=0)
Try to parse Block from a wire buffer.
Definition: block.cpp:162
#define NFD_LOG_INIT(name)
Definition: logger.hpp:31
void ping(connection_hdl hdl, std::string const &payload, lib::error_code &ec)
Send a ping to a specific connection.
#define NFD_LOG_FACE_TRACE(msg)
Log a message at TRACE level.
const ssize_t MTU_UNLIMITED
indicates the transport has no limit on payload size
Definition: transport.hpp:91
void setRemoteUri(const FaceUri &uri)
Definition: transport.hpp:397
#define NFD_LOG_FACE_ERROR(msg)
Log a message at ERROR level.
static value const normal
Normal closure, meaning that the purpose for which the connection was established has been fulfilled...
Definition: close.hpp:76
lib::weak_ptr< void > connection_hdl
A handle to uniquely identify a connection.
Represents a TLV element of the NDN packet format.
Definition: block.hpp:44
WebSocketTransport(websocketpp::connection_hdl hdl, websocket::Server &server, time::milliseconds pingInterval)
void setLinkType(ndn::nfd::LinkType linkType)
Definition: transport.hpp:427
connection_ptr get_con_from_hdl(connection_hdl hdl, lib::error_code &ec)
Retrieves a connection_ptr from a connection_hdl (exception free)
Definition: endpoint.hpp:643
const uint8_t * wire() const
Definition: block.hpp:250
void receiveMessage(const std::string &msg)
Translates a message into a Block and delivers it to the link service.
void setMtu(ssize_t mtu)
Definition: transport.cpp:126
the transport is being closed due to a failure
void setScope(ndn::nfd::FaceScope scope)
Definition: transport.hpp:409
Scheduler & getScheduler()
Returns the global Scheduler instance for the calling thread.
Definition: global.cpp:70
#define NFD_LOG_FACE_DEBUG(msg)
Log a message at DEBUG level.
void receive(const Block &packet, const EndpointId &endpoint=0)
Pass a received link-layer packet to the upper layer for further processing.
Definition: transport.cpp:113
size_t size() const
Return the size of the encoded wire, i.e., of the whole TLV.
Definition: block.cpp:294
static bool isLoopback(const boost::asio::ip::address &addr)
TransportState getState() const
Definition: transport.hpp:451
Copyright (c) 2011-2015 Regents of the University of California.
Definition: ndn-common.hpp:39
the transport is closed, and can be safely deallocated
void setLocalUri(const FaceUri &uri)
Definition: transport.hpp:385
PacketCounter nOutPings
count of outgoing Pings
PacketCounter nInPongs
count of incoming Pongs
the transport is being closed gracefully, either by the peer or by a call to close() ...
represents the underlying protocol and address used by a Face
Definition: face-uri.hpp:44
void cancel()
Cancel the operation.
A Transport that communicates on a WebSocket connection.
void close(connection_hdl hdl, close::status::value const code, std::string const &reason, lib::error_code &ec)
void setState(TransportState newState)
set transport state
Definition: transport.cpp:187
void send(connection_hdl hdl, std::string const &payload, frame::opcode::value op, lib::error_code &ec)
Create a message and add it to the outgoing send queue (exception free)
void doClose() final
performs Transport specific operations to close the transport
#define NFD_LOG_FACE_WARN(msg)
Log a message at WARN level.
boost::chrono::milliseconds milliseconds
Definition: time.hpp:48