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-2023, 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::face {
30 
31 NFD_LOG_INIT(WebSocketTransport);
32 
33 static bool
34 isLoopback(const boost::asio::ip::address& addr)
35 {
36  if (addr.is_loopback()) {
37  return true;
38  }
39 
40  // Workaround for loopback IPv4-mapped IPv6 addresses
41  // see https://svn.boost.org/trac/boost/ticket/9084
42  if (addr.is_v6()) {
43  auto addr6 = addr.to_v6();
44  if (addr6.is_v4_mapped()) {
45  return boost::asio::ip::make_address_v4(boost::asio::ip::v4_mapped, addr6).is_loopback();
46  }
47  }
48 
49  return false;
50 }
51 
52 WebSocketTransport::WebSocketTransport(websocketpp::connection_hdl hdl,
53  websocket::Server& server,
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())) {
65  this->setScope(ndn::nfd::FACE_SCOPE_LOCAL);
66  }
67  else {
68  this->setScope(ndn::nfd::FACE_SCOPE_NON_LOCAL);
69  }
70 
71  this->setPersistency(ndn::nfd::FACE_PERSISTENCY_ON_DEMAND);
72  this->setLinkType(ndn::nfd::LINK_TYPE_POINT_TO_POINT);
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.data(), packet.size(),
87  websocketpp::frame::opcode::binary, error);
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 nfd::face
void setScope(ndn::nfd::FaceScope scope) noexcept
Definition: transport.hpp:355
void receive(const Block &packet, const EndpointId &endpoint={})
Pass a received link-layer packet to the upper layer for further processing.
Definition: transport.cpp:101
void setPersistency(ndn::nfd::FacePersistency newPersistency)
Changes the persistency setting of the transport.
Definition: transport.cpp:152
void setMtu(ssize_t mtu) noexcept
Definition: transport.cpp:114
TransportState getState() const noexcept
Returns the current transport state.
Definition: transport.hpp:300
void setState(TransportState newState)
Set transport state.
Definition: transport.cpp:175
void setLocalUri(const FaceUri &uri) noexcept
Definition: transport.hpp:343
void setLinkType(ndn::nfd::LinkType linkType) noexcept
Definition: transport.hpp:361
void setRemoteUri(const FaceUri &uri) noexcept
Definition: transport.hpp:349
PacketCounter nInPongs
Count of incoming pongs.
PacketCounter nOutPings
Count of outgoing pings.
void doClose() final
Performs Transport specific operations to close the transport.
WebSocketTransport(websocketpp::connection_hdl hdl, websocket::Server &server, time::milliseconds pingInterval)
void receiveMessage(const std::string &msg)
Translates a message into a Block and delivers it to the link service.
#define NFD_LOG_FACE_ERROR(msg)
Log a message at ERROR level.
#define NFD_LOG_FACE_DEBUG(msg)
Log a message at DEBUG level.
#define NFD_LOG_FACE_WARN(msg)
Log a message at WARN level.
#define NFD_LOG_FACE_TRACE(msg)
Log a message at TRACE level.
#define NFD_LOG_INIT(name)
Definition: logger.hpp:31
static bool isLoopback(const boost::asio::ip::address &addr)
@ CLOSED
the transport is closed, and can be safely deallocated
@ CLOSING
the transport is being closed gracefully, either by the peer or by a call to close()
@ FAILED
the transport is being closed due to a failure
constexpr ssize_t MTU_UNLIMITED
Indicates that the transport has no limit on payload size.
Definition: transport.hpp:101
websocketpp::server< websocketpp::config::asio > Server
Definition: websocketpp.hpp:47
ndn::Scheduler & getScheduler()
Returns the global Scheduler instance for the calling thread.
Definition: global.cpp:45