face: Implement WebSocket channel, face, and factory.

Change-Id: Ic4dbb1abdbbdbec028746ba14b11be8ab9cc1edb
Refs: #1468
diff --git a/daemon/face/websocket-channel.cpp b/daemon/face/websocket-channel.cpp
new file mode 100644
index 0000000..db7fdc0
--- /dev/null
+++ b/daemon/face/websocket-channel.cpp
@@ -0,0 +1,127 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014  Regents of the University of California,
+ *                     Arizona Board of Regents,
+ *                     Colorado State University,
+ *                     University Pierre & Marie Curie, Sorbonne University,
+ *                     Washington University in St. Louis,
+ *                     Beijing Institute of Technology,
+ *                     The University of Memphis
+ *
+ * This file is part of NFD (Named Data Networking Forwarding Daemon).
+ * See AUTHORS.md for complete list of NFD authors and contributors.
+ *
+ * NFD is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
+ *
+ * NFD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+ * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE.  See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * NFD, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+#include "websocket-channel.hpp"
+#include "core/face-uri.hpp"
+
+namespace nfd {
+
+NFD_LOG_INIT("WebSocketChannel");
+
+using namespace boost::asio;
+
+WebSocketChannel::WebSocketChannel(const websocket::Endpoint& localEndpoint)
+  : m_localEndpoint(localEndpoint)
+  , m_isListening(false)
+{
+  // Setup WebSocket server
+  m_server.clear_access_channels(websocketpp::log::alevel::all);
+  m_server.clear_error_channels(websocketpp::log::alevel::all);
+
+  m_server.set_message_handler(bind(&WebSocketChannel::handleMessage, this, _1, _2));
+  m_server.set_open_handler(bind(&WebSocketChannel::handleOpen, this, _1));
+  m_server.set_close_handler(bind(&WebSocketChannel::handleClose, this, _1));
+  m_server.init_asio(&getGlobalIoService());
+
+  this->setUri(FaceUri(localEndpoint, "ws"));
+}
+
+WebSocketChannel::~WebSocketChannel()
+{
+}
+
+void
+WebSocketChannel::handleMessage(websocketpp::connection_hdl hdl,
+                                websocket::Server::message_ptr msg)
+{
+  ChannelFaceMap::iterator it = m_channelFaces.find(hdl);
+  if (it != m_channelFaces.end())
+    {
+      it->second->handleReceive(msg->get_payload());
+    }
+}
+
+void
+WebSocketChannel::handleOpen(websocketpp::connection_hdl hdl)
+{
+  std::string remote;
+  try
+    {
+      remote = "wsclient://" + m_server.get_con_from_hdl(hdl)->get_remote_endpoint();
+    }
+  catch (websocketpp::lib::error_code ec)
+    {
+      NFD_LOG_DEBUG("handleOpen: cannot get remote uri");
+      websocketpp::lib::error_code ecode;
+      m_server.close(hdl, websocketpp::close::status::normal, "closed by channel", ecode);
+    }
+  shared_ptr<WebSocketFace> face = make_shared<WebSocketFace>(FaceUri(remote), this->getUri(),
+                                                              hdl, boost::ref(m_server));
+  m_onFaceCreatedCallback(face);
+  m_channelFaces[hdl] = face;
+}
+
+void
+WebSocketChannel::handleClose(websocketpp::connection_hdl hdl)
+{
+  ChannelFaceMap::iterator it = m_channelFaces.find(hdl);
+  if (it != m_channelFaces.end())
+    {
+      NFD_LOG_DEBUG("handleClose: remove client");
+      m_channelFaces.erase(it);
+    }
+}
+
+
+void
+WebSocketChannel::listen(const FaceCreatedCallback& onFaceCreated)
+{
+  if (m_isListening)
+    {
+      throw Error("Listen already called on this channel");
+    }
+  m_isListening = true;
+
+  m_onFaceCreatedCallback = onFaceCreated;
+
+  try
+    {
+      m_server.listen(m_localEndpoint);
+    }
+  catch (websocketpp::lib::error_code ec)
+    {
+      throw Error("Failed to listen on local endpoint");
+    }
+
+  m_server.start_accept();
+}
+
+size_t
+WebSocketChannel::size() const
+{
+  return m_channelFaces.size();
+}
+
+} // namespace nfd
diff --git a/daemon/face/websocket-channel.hpp b/daemon/face/websocket-channel.hpp
new file mode 100644
index 0000000..05d8f99
--- /dev/null
+++ b/daemon/face/websocket-channel.hpp
@@ -0,0 +1,122 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014  Regents of the University of California,
+ *                     Arizona Board of Regents,
+ *                     Colorado State University,
+ *                     University Pierre & Marie Curie, Sorbonne University,
+ *                     Washington University in St. Louis,
+ *                     Beijing Institute of Technology,
+ *                     The University of Memphis
+ *
+ * This file is part of NFD (Named Data Networking Forwarding Daemon).
+ * See AUTHORS.md for complete list of NFD authors and contributors.
+ *
+ * NFD is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
+ *
+ * NFD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+ * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE.  See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * NFD, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+#ifndef NFD_DAEMON_FACE_WEBSOCKET_CHANNEL_HPP
+#define NFD_DAEMON_FACE_WEBSOCKET_CHANNEL_HPP
+
+#include "channel.hpp"
+#include "core/global-io.hpp"
+#include "core/scheduler.hpp"
+#include "websocket-face.hpp"
+
+namespace nfd {
+
+/**
+ * \brief Class implementing WebSocket-based channel to create faces
+ *
+ *
+ */
+class WebSocketChannel : public Channel
+{
+public:
+  /**
+   * \brief Exception of WebSocketChannel
+   */
+  class Error : public std::runtime_error
+  {
+  public:
+    explicit
+    Error(const std::string& what)
+      : runtime_error(what)
+    {
+    }
+  };
+
+  /**
+   * \brief Create WebSocket channel for the local endpoint
+   *
+   * To enable creation of faces upon incoming connections,
+   * one needs to explicitly call WebSocketChannel::listen method.
+   * The created socket is bound to the localEndpoint.
+   *
+   * \throw WebSocketChannel::Error if bind on the socket fails
+   */
+  explicit
+  WebSocketChannel(const websocket::Endpoint& localEndpoint);
+
+  virtual
+  ~WebSocketChannel();
+
+  /**
+   * \brief Enable listening on the local endpoint, accept connections,
+   *        and create faces when remote host makes a connection
+   * \param onFaceCreated  Callback to notify successful creation of the face
+   *
+   * \throws WebSocketChannel::Error if called multiple times
+   */
+  void
+  listen(const FaceCreatedCallback& onFaceCreated);
+
+  /**
+   * \brief Get number of faces in the channel
+   */
+  size_t
+  size() const;
+
+private:
+  void
+  handleMessage(websocketpp::connection_hdl hdl, websocket::Server::message_ptr msg);
+
+  void
+  handleOpen(websocketpp::connection_hdl hdl);
+
+  void
+  handleClose(websocketpp::connection_hdl hdl);
+
+private:
+  websocket::Endpoint m_localEndpoint;
+
+  websocket::Server m_server;
+
+  /**
+   * Callbacks for face creation.
+   * New communications are detected using async_receive_from.
+   * Its handler has a fixed signature. No space for the face callback
+   */
+  FaceCreatedCallback m_onFaceCreatedCallback;
+
+  typedef std::map< websocketpp::connection_hdl, shared_ptr<WebSocketFace> > ChannelFaceMap;
+  ChannelFaceMap m_channelFaces;
+
+  /**
+   * \brief If true, it means the function listen has already been called
+   */
+  bool m_isListening;
+
+};
+
+} // namespace nfd
+
+#endif // NFD_DAEMON_FACE_WEBSOCKET_CHANNEL_HPP
diff --git a/daemon/face/websocket-face.cpp b/daemon/face/websocket-face.cpp
new file mode 100644
index 0000000..4712cfc
--- /dev/null
+++ b/daemon/face/websocket-face.cpp
@@ -0,0 +1,97 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014  Regents of the University of California,
+ *                     Arizona Board of Regents,
+ *                     Colorado State University,
+ *                     University Pierre & Marie Curie, Sorbonne University,
+ *                     Washington University in St. Louis,
+ *                     Beijing Institute of Technology,
+ *                     The University of Memphis
+ *
+ * This file is part of NFD (Named Data Networking Forwarding Daemon).
+ * See AUTHORS.md for complete list of NFD authors and contributors.
+ *
+ * NFD is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
+ *
+ * NFD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+ * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE.  See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * NFD, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+#include "websocket-face.hpp"
+
+namespace nfd {
+
+NFD_LOG_INIT("WebSocketFace");
+
+WebSocketFace::WebSocketFace(const FaceUri& remoteUri, const FaceUri& localUri,
+                             websocketpp::connection_hdl hdl,
+                             websocket::Server& server)
+  : Face(remoteUri, localUri)
+  , m_handle(hdl)
+  , m_server(server)
+  , m_closed(false)
+{
+}
+
+
+void
+WebSocketFace::sendInterest(const Interest& interest)
+{
+  this->onSendInterest(interest);
+  const Block& payload = interest.wireEncode();
+  m_server.send(m_handle, payload.wire(), payload.size(), websocketpp::frame::opcode::binary);
+}
+
+void
+WebSocketFace::sendData(const Data& data)
+{
+  this->onSendData(data);
+  const Block& payload = data.wireEncode();
+  m_server.send(m_handle, payload.wire(), payload.size(), websocketpp::frame::opcode::binary);
+}
+
+void
+WebSocketFace::close()
+{
+  if (m_closed == false)
+    {
+      m_closed = true;
+      websocketpp::lib::error_code ecode;
+      m_server.close(m_handle, websocketpp::close::status::normal, "closed by nfd", ecode);
+    }
+}
+
+void
+WebSocketFace::handleReceive(const std::string& msg)
+{
+  // Copy message into Face internal buffer
+  BOOST_ASSERT(msg.size() <= MAX_NDN_PACKET_SIZE);
+
+  // Try to parse message data
+  bool isOk = true;
+  Block element;
+  isOk = Block::fromBuffer(reinterpret_cast<const uint8_t*>(msg.c_str()), msg.size(), element);
+  if (!isOk)
+    {
+      NFD_LOG_TRACE("[id:" << this->getId()
+                    << "] Received invalid NDN packet of length ["
+                    << msg.size() << "]");
+      return;
+    }
+
+  if (!this->decodeAndDispatchInput(element))
+    {
+      NFD_LOG_WARN("[id:" << this->getId()
+                   << "] Received unrecognized block of type ["
+                   << element.type() << "]");
+      // ignore unknown packet and proceed
+    }
+}
+
+} // namespace nfd
diff --git a/daemon/face/websocket-face.hpp b/daemon/face/websocket-face.hpp
new file mode 100644
index 0000000..3f2a932
--- /dev/null
+++ b/daemon/face/websocket-face.hpp
@@ -0,0 +1,77 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014  Regents of the University of California,
+ *                     Arizona Board of Regents,
+ *                     Colorado State University,
+ *                     University Pierre & Marie Curie, Sorbonne University,
+ *                     Washington University in St. Louis,
+ *                     Beijing Institute of Technology,
+ *                     The University of Memphis
+ *
+ * This file is part of NFD (Named Data Networking Forwarding Daemon).
+ * See AUTHORS.md for complete list of NFD authors and contributors.
+ *
+ * NFD is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
+ *
+ * NFD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+ * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE.  See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * NFD, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+#ifndef NFD_DAEMON_FACE_WEBSOCKET_FACE_HPP
+#define NFD_DAEMON_FACE_WEBSOCKET_FACE_HPP
+
+#include "face.hpp"
+#include "core/logger.hpp"
+
+#ifndef HAVE_WEBSOCKET
+#error "Cannot include this file when WebSocket support is not enabled"
+#endif // HAVE_WEBSOCKET
+
+#include "websocketpp.hpp"
+
+namespace nfd {
+
+namespace websocket {
+typedef boost::asio::ip::tcp::endpoint Endpoint;
+typedef websocketpp::server<websocketpp::config::asio> Server;
+} // namespace websocket
+
+
+/**
+ * \brief Implementation of Face abstraction that uses WebSocket
+ *        as underlying transport mechanism
+ */
+class WebSocketFace : public Face
+{
+public:
+  WebSocketFace(const FaceUri& remoteUri, const FaceUri& localUri,
+                websocketpp::connection_hdl hdl, websocket::Server& server);
+
+  // from Face
+  virtual void
+  sendInterest(const Interest& interest);
+
+  virtual void
+  sendData(const Data& data);
+
+  virtual void
+  close();
+
+  void
+  handleReceive(const std::string& msg);
+
+private:
+  websocketpp::connection_hdl m_handle;
+  websocket::Server& m_server;
+  bool m_closed;
+};
+
+} // namespace nfd
+
+#endif // NFD_DAEMON_FACE_WEBSOCKET_FACE_HPP
diff --git a/daemon/face/websocket-factory.cpp b/daemon/face/websocket-factory.cpp
new file mode 100644
index 0000000..224a75b
--- /dev/null
+++ b/daemon/face/websocket-factory.cpp
@@ -0,0 +1,84 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014  Regents of the University of California,
+ *                     Arizona Board of Regents,
+ *                     Colorado State University,
+ *                     University Pierre & Marie Curie, Sorbonne University,
+ *                     Washington University in St. Louis,
+ *                     Beijing Institute of Technology,
+ *                     The University of Memphis
+ *
+ * This file is part of NFD (Named Data Networking Forwarding Daemon).
+ * See AUTHORS.md for complete list of NFD authors and contributors.
+ *
+ * NFD is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
+ *
+ * NFD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+ * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE.  See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * NFD, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+#include "websocket-factory.hpp"
+
+namespace nfd {
+
+using namespace boost::asio;
+
+NFD_LOG_INIT("WebSocketFactory");
+
+WebSocketFactory::WebSocketFactory(const std::string& defaultPort)
+  : m_defaultPort(defaultPort)
+{
+}
+
+shared_ptr<WebSocketChannel>
+WebSocketFactory::createChannel(const websocket::Endpoint& endpoint)
+{
+  shared_ptr<WebSocketChannel> channel = findChannel(endpoint);
+  if (static_cast<bool>(channel))
+    return channel;
+
+  channel = make_shared<WebSocketChannel>(boost::cref(endpoint));
+  m_channels[endpoint] = channel;
+
+  return channel;
+}
+
+shared_ptr<WebSocketChannel>
+WebSocketFactory::createChannel(const std::string& localIPAddress,
+                                uint16_t localPort)
+{
+  boost::system::error_code ec;
+  ip::address address = ip::address::from_string(localIPAddress, ec);
+  if (ec)
+    {
+      throw Error("Invalid address format: " + localIPAddress);
+    }
+  websocket::Endpoint endpoint(address, localPort);
+  return createChannel(endpoint);
+}
+
+shared_ptr<WebSocketChannel>
+WebSocketFactory::findChannel(const websocket::Endpoint& localEndpoint)
+{
+  ChannelMap::iterator i = m_channels.find(localEndpoint);
+  if (i != m_channels.end())
+    return i->second;
+  else
+    return shared_ptr<WebSocketChannel>();
+}
+
+void
+WebSocketFactory::createFace(const FaceUri& uri,
+                             const FaceCreatedCallback& onCreated,
+                             const FaceConnectFailedCallback& onConnectFailed)
+{
+  throw Error("WebSocketFactory does not support 'createFace' operation");
+}
+
+} // namespace nfd
diff --git a/daemon/face/websocket-factory.hpp b/daemon/face/websocket-factory.hpp
new file mode 100644
index 0000000..b241fcc
--- /dev/null
+++ b/daemon/face/websocket-factory.hpp
@@ -0,0 +1,108 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014  Regents of the University of California,
+ *                     Arizona Board of Regents,
+ *                     Colorado State University,
+ *                     University Pierre & Marie Curie, Sorbonne University,
+ *                     Washington University in St. Louis,
+ *                     Beijing Institute of Technology,
+ *                     The University of Memphis
+ *
+ * This file is part of NFD (Named Data Networking Forwarding Daemon).
+ * See AUTHORS.md for complete list of NFD authors and contributors.
+ *
+ * NFD is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
+ *
+ * NFD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+ * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE.  See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * NFD, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+#ifndef NFD_DAEMON_FACE_WEBSOCKET_FACTORY_HPP
+#define NFD_DAEMON_FACE_WEBSOCKET_FACTORY_HPP
+
+#include "protocol-factory.hpp"
+#include "websocket-channel.hpp"
+
+
+namespace nfd {
+
+class WebSocketFactory : public ProtocolFactory
+{
+public:
+  /**
+   * \brief Exception of WebSocketFactory
+   */
+  class Error : public ProtocolFactory::Error
+  {
+  public:
+    explicit
+    Error(const std::string& what)
+      : ProtocolFactory::Error(what)
+    {
+    }
+  };
+
+  explicit
+  WebSocketFactory(const std::string& defaultPort);
+
+  /**
+   * \brief Create WebSocket-based channel using websocket::Endpoint
+   *
+   * websocket::Endpoint is really an alias for boost::asio::ip::tcp::endpoint.
+   *
+   * If this method called twice with the same endpoint, only one channel
+   * will be created.  The second call will just retrieve the existing
+   * channel.
+   *
+   * \returns always a valid pointer to a WebSocketChannel object, an exception
+   *          is thrown if it cannot be created.
+   *
+   * \throws WebSocketFactory::Error
+   *
+   */
+  shared_ptr<WebSocketChannel>
+  createChannel(const websocket::Endpoint& localEndpoint);
+
+  /**
+   * \brief Create WebSocket-based channel using specified ip address and port number
+   *
+   * \throws WebSocketFactory::Error
+   */
+  shared_ptr<WebSocketChannel>
+  createChannel(const std::string& localIPAddress,
+                uint16_t localPort);
+
+  // from Factory
+  virtual void
+  createFace(const FaceUri& uri,
+             const FaceCreatedCallback& onCreated,
+             const FaceConnectFailedCallback& onConnectFailed);
+
+private:
+
+  /**
+   * \brief Look up WebSocketChannel using specified local endpoint
+   *
+   * \returns shared pointer to the existing WebSocketChannel object
+   *          or empty shared pointer when such channel does not exist
+   *
+   * \throws never
+   */
+  shared_ptr<WebSocketChannel>
+  findChannel(const websocket::Endpoint& localEndpoint);
+
+  typedef std::map< websocket::Endpoint, shared_ptr<WebSocketChannel> > ChannelMap;
+  ChannelMap m_channels;
+
+  std::string m_defaultPort;
+};
+
+} // namespace nfd
+
+#endif // NFD_DAEMON_FACE_WEBSOCKET_FACTORY_HPP
diff --git a/daemon/face/websocketpp.hpp b/daemon/face/websocketpp.hpp
new file mode 100644
index 0000000..1e934b6
--- /dev/null
+++ b/daemon/face/websocketpp.hpp
@@ -0,0 +1,36 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
+/**
+ * Copyright (c) 2014  Regents of the University of California,
+ *                     Arizona Board of Regents,
+ *                     Colorado State University,
+ *                     University Pierre & Marie Curie, Sorbonne University,
+ *                     Washington University in St. Louis,
+ *                     Beijing Institute of Technology,
+ *                     The University of Memphis
+ *
+ * This file is part of NFD (Named Data Networking Forwarding Daemon).
+ * See AUTHORS.md for complete list of NFD authors and contributors.
+ *
+ * NFD is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
+ *
+ * NFD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+ * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE.  See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * NFD, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef NFD_DAEMON_FACE_WEBSOCKETPP_HPP
+#define NFD_DAEMON_FACE_WEBSOCKETPP_HPP
+
+// suppress websocketpp warnings
+#pragma GCC system_header
+#pragma clang system_header
+
+#include "websocketpp/config/asio_no_tls.hpp"
+#include "websocketpp/server.hpp"
+
+#endif // NFD_DAEMON_FACE_WEBSOCKETPP_HPP