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-2019, 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 
32 NFD_LOG_INIT(WebSocketTransport);
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 
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, const EndpointId&)
82 {
83  NFD_LOG_FACE_TRACE(__func__);
84 
85  websocketpp::lib::error_code error;
86  m_server.send(m_handle, packet.wire(), 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 face
178 } // namespace nfd
void receiveMessage(const std::string &msg)
Translates a message into a Block and delivers it to the link service.
void setLocalUri(const FaceUri &uri)
Definition: transport.hpp:394
#define NFD_LOG_FACE_TRACE(msg)
Log a message at TRACE level.
void setScope(ndn::nfd::FaceScope scope)
Definition: transport.hpp:418
const ssize_t MTU_UNLIMITED
indicates the transport has no limit on payload size
Definition: transport.hpp:91
void setMtu(ssize_t mtu)
Definition: transport.hpp:448
#define NFD_LOG_FACE_DEBUG(msg)
Log a message at DEBUG level.
websocketpp::server< websocketpp::config::asio > Server
Definition: websocketpp.hpp:46
void doClose() final
performs Transport specific operations to close the transport
WebSocketTransport(websocketpp::connection_hdl hdl, websocket::Server &server, time::milliseconds pingInterval)
uint64_t EndpointId
Identifies a remote endpoint on the link.
Definition: face-common.hpp:65
the transport is being closed due to a failure
Scheduler & getScheduler()
Returns the global Scheduler instance for the calling thread.
Definition: global.cpp:45
#define NFD_LOG_FACE_WARN(msg)
Log a message at WARN level.
static bool isLoopback(const boost::asio::ip::address &addr)
Copyright (c) 2014-2015, Regents of the University of California, Arizona Board of Regents...
Definition: algorithm.hpp:32
the transport is closed, and can be safely deallocated
void setLinkType(ndn::nfd::LinkType linkType)
Definition: transport.hpp:436
the transport is being closed gracefully, either by the peer or by a call to close() ...
void setPersistency(ndn::nfd::FacePersistency newPersistency)
changes face persistency setting
Definition: transport.cpp:150
#define NFD_LOG_INIT(name)
Definition: logger.hpp:31
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:115
TransportState getState() const
Definition: transport.hpp:467
void setState(TransportState newState)
set transport state
Definition: transport.cpp:173
void setRemoteUri(const FaceUri &uri)
Definition: transport.hpp:406
PacketCounter nOutPings
count of outgoing Pings
PacketCounter nInPongs
count of incoming Pongs
#define NFD_LOG_FACE_ERROR(msg)
Log a message at ERROR level.