face: UnixStream{Face,Channel,ChannelFactory} implementation.

refs: #1174

Change-Id: I14d1e357c96a02995355e7970323fe40847580aa
diff --git a/daemon/face/tcp-channel-factory.hpp b/daemon/face/tcp-channel-factory.hpp
index 1a26738..171c24f 100644
--- a/daemon/face/tcp-channel-factory.hpp
+++ b/daemon/face/tcp-channel-factory.hpp
@@ -20,9 +20,13 @@
    */
   struct Error : public ChannelFactory<tcp::Endpoint, TcpChannel>::Error
   {
-    Error(const std::string& what) : ChannelFactory<tcp::Endpoint, TcpChannel>::Error(what) {}
+    Error(const std::string& what)
+      : ChannelFactory<tcp::Endpoint, TcpChannel>::Error(what)
+    {
+    }
   };
 
+  explicit
   TcpChannelFactory(boost::asio::io_service& ioService);
 
   /**
@@ -58,6 +62,7 @@
   shared_ptr<TcpChannel>
   create(const std::string& localHost, const std::string& localPort);
 
+private:
   /**
    * \brief Look up TcpChannel using specified local endpoint
    *
@@ -68,7 +73,7 @@
    */
   shared_ptr<TcpChannel>
   find(const tcp::Endpoint& localEndpoint);
-  
+
 private:
   boost::asio::io_service& m_ioService;
 };
diff --git a/daemon/face/tcp-channel.hpp b/daemon/face/tcp-channel.hpp
index e94747f..4cca5c5 100644
--- a/daemon/face/tcp-channel.hpp
+++ b/daemon/face/tcp-channel.hpp
@@ -11,12 +11,12 @@
 #include "core/monotonic_deadline_timer.hpp"
 #include "tcp-face.hpp"
 
-namespace tcp {
-typedef boost::asio::ip::tcp::endpoint Endpoint;
-} // namespace tcp
-
 namespace nfd {
 
+namespace tcp {
+  typedef boost::asio::ip::tcp::endpoint Endpoint;
+} // namespace tcp
+
 /**
  * \brief Class implementing TCP-based channel to create faces
  *
diff --git a/daemon/face/tcp-face.cpp b/daemon/face/tcp-face.cpp
index e867483..774a4d0 100644
--- a/daemon/face/tcp-face.cpp
+++ b/daemon/face/tcp-face.cpp
@@ -18,5 +18,4 @@
 {
 }
 
-
 } // namespace nfd
diff --git a/daemon/face/tcp-face.hpp b/daemon/face/tcp-face.hpp
index af45c6c..98593a0 100644
--- a/daemon/face/tcp-face.hpp
+++ b/daemon/face/tcp-face.hpp
@@ -21,6 +21,7 @@
 public:
   typedef boost::asio::ip::tcp protocol;
 
+  explicit
   TcpFace(const shared_ptr<protocol::socket>& socket);
 };
 
diff --git a/daemon/face/unix-stream-channel-factory.cpp b/daemon/face/unix-stream-channel-factory.cpp
new file mode 100644
index 0000000..cc86333
--- /dev/null
+++ b/daemon/face/unix-stream-channel-factory.cpp
@@ -0,0 +1,51 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (C) 2014 Named Data Networking Project
+ * See COPYING for copyright and distribution information.
+ */
+
+#include "unix-stream-channel-factory.hpp"
+
+#if BOOST_VERSION >= 104800
+#include <boost/filesystem.hpp> // for canonical()
+#endif
+
+namespace nfd {
+
+UnixStreamChannelFactory::UnixStreamChannelFactory(boost::asio::io_service& ioService)
+  : m_ioService(ioService)
+{
+}
+
+shared_ptr<UnixStreamChannel>
+UnixStreamChannelFactory::create(const std::string& unixSocketPath)
+{
+#if BOOST_VERSION >= 104800
+  boost::filesystem::path p(unixSocketPath);
+  p = boost::filesystem::canonical(p.parent_path()) / p.filename();
+  unix_stream::Endpoint endpoint(p.string());
+#else
+  unix_stream::Endpoint endpoint(unixSocketPath);
+#endif
+
+  shared_ptr<UnixStreamChannel> channel = find(endpoint);
+  if (channel)
+    return channel;
+
+  channel = make_shared<UnixStreamChannel>(boost::ref(m_ioService),
+                                           boost::cref(endpoint));
+  m_channels[endpoint] = channel;
+  return channel;
+}
+
+shared_ptr<UnixStreamChannel>
+UnixStreamChannelFactory::find(const unix_stream::Endpoint& endpoint)
+{
+  ChannelMap::iterator i = m_channels.find(endpoint);
+  if (i != m_channels.end())
+    return i->second;
+  else
+    return shared_ptr<UnixStreamChannel>();
+}
+
+} // namespace nfd
diff --git a/daemon/face/unix-stream-channel-factory.hpp b/daemon/face/unix-stream-channel-factory.hpp
new file mode 100644
index 0000000..8d0a6e7
--- /dev/null
+++ b/daemon/face/unix-stream-channel-factory.hpp
@@ -0,0 +1,65 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (C) 2014 Named Data Networking Project
+ * See COPYING for copyright and distribution information.
+ */
+
+#ifndef NFD_FACE_UNIX_STREAM_CHANNEL_FACTORY_HPP
+#define NFD_FACE_UNIX_STREAM_CHANNEL_FACTORY_HPP
+
+#include "channel-factory.hpp"
+#include "unix-stream-channel.hpp"
+
+namespace nfd {
+
+class UnixStreamChannelFactory : public ChannelFactory<unix_stream::Endpoint, UnixStreamChannel>
+{
+public:
+  /**
+   * \brief Exception of UnixStreamChannelFactory
+   */
+  struct Error : public ChannelFactory<unix_stream::Endpoint, UnixStreamChannel>::Error
+  {
+    Error(const std::string& what)
+      : ChannelFactory<unix_stream::Endpoint, UnixStreamChannel>::Error(what)
+    {
+    }
+  };
+
+  explicit
+  UnixStreamChannelFactory(boost::asio::io_service& ioService);
+
+  /**
+   * \brief Create stream-oriented Unix channel using specified socket path
+   *
+   * If this method is called twice with the same path, only one channel
+   * will be created.  The second call will just retrieve the existing
+   * channel.
+   *
+   * \returns always a valid pointer to a UnixStreamChannel object,
+   *          an exception will be thrown if the channel cannot be created.
+   *
+   * \throws UnixStreamChannelFactory::Error
+   */
+  shared_ptr<UnixStreamChannel>
+  create(const std::string& unixSocketPath);
+
+private:
+  /**
+   * \brief Look up UnixStreamChannel using specified endpoint
+   *
+   * \returns shared pointer to the existing UnixStreamChannel object
+   *          or empty shared pointer when such channel does not exist
+   *
+   * \throws never
+   */
+  shared_ptr<UnixStreamChannel>
+  find(const unix_stream::Endpoint& endpoint);
+
+private:
+  boost::asio::io_service& m_ioService;
+};
+
+} // namespace nfd
+
+#endif // NFD_FACE_UNIX_STREAM_CHANNEL_FACTORY_HPP
diff --git a/daemon/face/unix-stream-channel.cpp b/daemon/face/unix-stream-channel.cpp
new file mode 100644
index 0000000..428d33e
--- /dev/null
+++ b/daemon/face/unix-stream-channel.cpp
@@ -0,0 +1,101 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (C) 2014 Named Data Networking Project
+ * See COPYING for copyright and distribution information.
+ */
+
+#include "unix-stream-channel.hpp"
+
+#include <boost/filesystem.hpp>
+
+namespace nfd {
+
+NFD_LOG_INIT("UnixStreamChannel");
+
+using namespace boost::asio::local;
+
+UnixStreamChannel::UnixStreamChannel(boost::asio::io_service& ioService,
+                                     const unix_stream::Endpoint& endpoint)
+  : m_ioService(ioService)
+  , m_endpoint(endpoint)
+{
+}
+
+UnixStreamChannel::~UnixStreamChannel()
+{
+  if (m_acceptor)
+    {
+      // use the non-throwing variants during destruction
+      // and ignore any errors
+      boost::system::error_code error;
+      m_acceptor->close(error);
+      boost::filesystem::remove(m_endpoint.path(), error);
+    }
+}
+
+void
+UnixStreamChannel::listen(const FaceCreatedCallback& onFaceCreated,
+                          const ConnectFailedCallback& onAcceptFailed,
+                          int backlog/* = acceptor::max_connections*/)
+{
+  if (m_acceptor) // already listening
+    return;
+
+  namespace fs = boost::filesystem;
+  fs::path p(m_endpoint.path());
+  if (fs::symlink_status(p).type() == fs::socket_file)
+    {
+      // for safety, remove an already existing file only if it's a socket
+      fs::remove(p);
+    }
+
+  m_acceptor = make_shared<stream_protocol::acceptor>(boost::ref(m_ioService));
+  m_acceptor->open(m_endpoint.protocol());
+  m_acceptor->bind(m_endpoint);
+  m_acceptor->listen(backlog);
+
+  shared_ptr<stream_protocol::socket> clientSocket =
+    make_shared<stream_protocol::socket>(boost::ref(m_ioService));
+  m_acceptor->async_accept(*clientSocket,
+                           bind(&UnixStreamChannel::handleSuccessfulAccept, this, _1,
+                                clientSocket, onFaceCreated, onAcceptFailed));
+}
+
+void
+UnixStreamChannel::createFace(const shared_ptr<stream_protocol::socket>& socket,
+                              const FaceCreatedCallback& onFaceCreated)
+{
+  shared_ptr<UnixStreamFace> face = make_shared<UnixStreamFace>(boost::cref(socket));
+  onFaceCreated(face);
+}
+
+void
+UnixStreamChannel::handleSuccessfulAccept(const boost::system::error_code& error,
+                                          const shared_ptr<stream_protocol::socket>& socket,
+                                          const FaceCreatedCallback& onFaceCreated,
+                                          const ConnectFailedCallback& onAcceptFailed)
+{
+  if (error) {
+    if (error == boost::system::errc::operation_canceled) // when socket is closed by someone
+      return;
+
+    NFD_LOG_DEBUG("Connection failed: "
+                  << error.category().message(error.value()));
+
+    onAcceptFailed("Connection failed: " +
+                   error.category().message(error.value()));
+    return;
+  }
+
+  // prepare accepting the next connection
+  shared_ptr<stream_protocol::socket> clientSocket =
+    make_shared<stream_protocol::socket>(boost::ref(m_ioService));
+  m_acceptor->async_accept(*clientSocket,
+                           bind(&UnixStreamChannel::handleSuccessfulAccept, this, _1,
+                                clientSocket, onFaceCreated, onAcceptFailed));
+
+  NFD_LOG_DEBUG("[" << m_endpoint << "] << Incoming connection");
+  createFace(socket, onFaceCreated);
+}
+
+} // namespace nfd
diff --git a/daemon/face/unix-stream-channel.hpp b/daemon/face/unix-stream-channel.hpp
new file mode 100644
index 0000000..bd0a81e
--- /dev/null
+++ b/daemon/face/unix-stream-channel.hpp
@@ -0,0 +1,84 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (C) 2014 Named Data Networking Project
+ * See COPYING for copyright and distribution information.
+ */
+
+#ifndef NFD_FACE_UNIX_STREAM_CHANNEL_HPP
+#define NFD_FACE_UNIX_STREAM_CHANNEL_HPP
+
+#include "common.hpp"
+#include "unix-stream-face.hpp"
+
+namespace nfd {
+
+namespace unix_stream {
+  typedef boost::asio::local::stream_protocol::endpoint Endpoint;
+} // namespace unix_stream
+
+/**
+ * \brief Class implementing a local channel to create faces
+ *
+ * Channel can create faces as a response to incoming IPC connections
+ * (UnixStreamChannel::listen needs to be called for that to work).
+ */
+class UnixStreamChannel // : protected SessionBasedChannel
+{
+public:
+  /**
+   * \brief Prototype for the callback called when a face is created
+   *        (as a response to an incoming connection)
+   */
+  typedef function<void(const shared_ptr<UnixStreamFace>& newFace)> FaceCreatedCallback;
+
+  /**
+   * \brief Prototype for the callback that is called when a face
+   *        fails to be created
+   */
+  typedef function<void(const std::string& reason)> ConnectFailedCallback;
+
+  /**
+   * \brief Create UnixStream channel for the specified endpoint
+   *
+   * To enable creation of faces upon incoming connections, one
+   * needs to explicitly call UnixStreamChannel::listen method.
+   */
+  UnixStreamChannel(boost::asio::io_service& ioService,
+                    const unix_stream::Endpoint& endpoint);
+
+  ~UnixStreamChannel();
+
+  /**
+   * \brief Enable listening on the local endpoint, accept connections,
+   *        and create faces when a connection is made
+   * \param onFaceCreated  Callback to notify successful creation of the face
+   * \param onAcceptFailed Callback to notify when channel fails (accept call
+   *                       returns an error)
+   * \param backlog        The maximum length of the queue of pending incoming
+   *                       connections
+   */
+  void
+  listen(const FaceCreatedCallback& onFaceCreated,
+         const ConnectFailedCallback& onAcceptFailed,
+         int backlog = boost::asio::local::stream_protocol::acceptor::max_connections);
+
+private:
+  void
+  createFace(const shared_ptr<boost::asio::local::stream_protocol::socket>& socket,
+             const FaceCreatedCallback& onFaceCreated);
+
+  void
+  handleSuccessfulAccept(const boost::system::error_code& error,
+                         const shared_ptr<boost::asio::local::stream_protocol::socket>& socket,
+                         const FaceCreatedCallback& onFaceCreated,
+                         const ConnectFailedCallback& onConnectFailed);
+
+private:
+  boost::asio::io_service& m_ioService;
+  unix_stream::Endpoint m_endpoint;
+  shared_ptr<boost::asio::local::stream_protocol::acceptor> m_acceptor;
+};
+
+} // namespace nfd
+
+#endif // NFD_FACE_UNIX_STREAM_CHANNEL_HPP
diff --git a/daemon/face/unix-stream-face.cpp b/daemon/face/unix-stream-face.cpp
new file mode 100644
index 0000000..de7c4f9
--- /dev/null
+++ b/daemon/face/unix-stream-face.cpp
@@ -0,0 +1,27 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (C) 2014 Named Data Networking Project
+ * See COPYING for copyright and distribution information.
+ */
+
+#include "unix-stream-face.hpp"
+
+namespace nfd {
+
+// The whole purpose of this file is to specialize the logger,
+// otherwise, everything could be put into the header file.
+
+NFD_LOG_INCLASS_TEMPLATE_SPECIALIZATION_DEFINE(StreamFace, UnixStreamFace::protocol, "UnixStreamFace");
+
+UnixStreamFace::UnixStreamFace(const shared_ptr<UnixStreamFace::protocol::socket>& socket)
+  : StreamFace<protocol>(socket)
+{
+}
+
+bool
+UnixStreamFace::isLocal() const
+{
+  return true;
+}
+
+} // namespace nfd
diff --git a/daemon/face/unix-stream-face.hpp b/daemon/face/unix-stream-face.hpp
new file mode 100644
index 0000000..c04bec2
--- /dev/null
+++ b/daemon/face/unix-stream-face.hpp
@@ -0,0 +1,37 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (C) 2014 Named Data Networking Project
+ * See COPYING for copyright and distribution information.
+ */
+
+#ifndef NFD_FACE_UNIX_STREAM_FACE_HPP
+#define NFD_FACE_UNIX_STREAM_FACE_HPP
+
+#include "stream-face.hpp"
+
+namespace nfd
+{
+
+/**
+ * \brief Implementation of Face abstraction that uses stream-oriented
+ *        Unix domain sockets as underlying transport mechanism
+ */
+class UnixStreamFace : public StreamFace<boost::asio::local::stream_protocol>
+{
+public:
+  typedef boost::asio::local::stream_protocol protocol;
+
+  explicit
+  UnixStreamFace(const shared_ptr<protocol::socket>& socket);
+
+  /** \brief Get whether face is connected to a local app
+   *
+   *  Always true for a UnixStreamFace.
+   */
+  virtual bool
+  isLocal() const;
+};
+
+} // namespace nfd
+
+#endif // NFD_FACE_UNIX_STREAM_FACE_HPP