face: make EthernetFace more robust against errors.

We now call .fail() instead of throwing an exception.

Also modernize the code with some C++11 features.
In particular, std::unique_ptr is now used to manage
the pcap instance.

Change-Id: I91200ff9ab64ddb2d86f082647043e42ca85f538
Refs: #1984
diff --git a/daemon/face/ethernet-face.cpp b/daemon/face/ethernet-face.cpp
index 4ffb9db..0e13844 100644
--- a/daemon/face/ethernet-face.cpp
+++ b/daemon/face/ethernet-face.cpp
@@ -64,6 +64,7 @@
                            const NetworkInterfaceInfo& interface,
                            const ethernet::Address& address)
   : Face(FaceUri(address), FaceUri::fromDev(interface.name))
+  , m_pcap(nullptr, pcap_close)
   , m_socket(socket)
 #if defined(__linux__)
   , m_interfaceIndex(interface.index)
@@ -76,7 +77,7 @@
                << m_srcAddress << " <--> " << m_destAddress);
   pcapInit();
 
-  int fd = pcap_get_selectable_fd(m_pcap);
+  int fd = pcap_get_selectable_fd(m_pcap.get());
   if (fd < 0)
     throw Error("pcap_get_selectable_fd() failed");
 
@@ -107,8 +108,6 @@
 
 EthernetFace::~EthernetFace()
 {
-  onFail.clear(); // no reason to call onFail anymore
-  close();
 }
 
 void
@@ -128,23 +127,25 @@
 void
 EthernetFace::close()
 {
-  if (m_pcap)
-    {
-      boost::system::error_code error;
-      m_socket->close(error); // ignore errors
-      pcap_close(m_pcap);
-      m_pcap = 0;
+  if (!m_pcap)
+    return;
 
-      fail("Face closed");
-    }
+  NFD_LOG_INFO("[id:" << getId() << ",endpoint:" << m_interfaceName
+               << "] Closing face");
+
+  boost::system::error_code error;
+  m_socket->cancel(error); // ignore errors
+  m_socket->close(error);  // ignore errors
+  m_pcap.reset(nullptr);
+
+  fail("Face closed");
 }
 
 void
 EthernetFace::pcapInit()
 {
-  char errbuf[PCAP_ERRBUF_SIZE];
-  errbuf[0] = '\0';
-  m_pcap = pcap_create(m_interfaceName.c_str(), errbuf);
+  char errbuf[PCAP_ERRBUF_SIZE] = {};
+  m_pcap.reset(pcap_create(m_interfaceName.c_str(), errbuf));
   if (!m_pcap)
     throw Error("pcap_create(): " + std::string(errbuf));
 
@@ -153,31 +154,31 @@
   // This corresponds to the BIOCIMMEDIATE ioctl on BSD-like systems (including OS X)
   // where libpcap uses a BPF device. On Linux this forces libpcap not to use TPACKET_V3,
   // even if the kernel supports it, thus preventing bug #1511.
-  pcap_set_immediate_mode(m_pcap, 1);
+  pcap_set_immediate_mode(m_pcap.get(), 1);
 #endif
 
-  if (pcap_activate(m_pcap) < 0)
+  if (pcap_activate(m_pcap.get()) < 0)
     throw Error("pcap_activate() failed");
 
-  if (pcap_set_datalink(m_pcap, DLT_EN10MB) < 0)
-    throw Error("pcap_set_datalink(): " + std::string(pcap_geterr(m_pcap)));
+  if (pcap_set_datalink(m_pcap.get(), DLT_EN10MB) < 0)
+    throw Error("pcap_set_datalink(): " + std::string(pcap_geterr(m_pcap.get())));
 
-  if (pcap_setdirection(m_pcap, PCAP_D_IN) < 0)
+  if (pcap_setdirection(m_pcap.get(), PCAP_D_IN) < 0)
     // no need to throw on failure, BPF will filter unwanted packets anyway
-    NFD_LOG_WARN("pcap_setdirection(): " << pcap_geterr(m_pcap));
+    NFD_LOG_WARN("pcap_setdirection(): " << pcap_geterr(m_pcap.get()));
 }
 
 void
 EthernetFace::setPacketFilter(const char* filterString)
 {
   bpf_program filter;
-  if (pcap_compile(m_pcap, &filter, filterString, 1, PCAP_NETMASK_UNKNOWN) < 0)
-    throw Error("pcap_compile(): " + std::string(pcap_geterr(m_pcap)));
+  if (pcap_compile(m_pcap.get(), &filter, filterString, 1, PCAP_NETMASK_UNKNOWN) < 0)
+    throw Error("pcap_compile(): " + std::string(pcap_geterr(m_pcap.get())));
 
-  int ret = pcap_setfilter(m_pcap, &filter);
+  int ret = pcap_setfilter(m_pcap.get(), &filter);
   pcap_freecode(&filter);
   if (ret < 0)
-    throw Error("pcap_setfilter(): " + std::string(pcap_geterr(m_pcap)));
+    throw Error("pcap_setfilter(): " + std::string(pcap_geterr(m_pcap.get())));
 }
 
 void
@@ -242,7 +243,7 @@
     {
       NFD_LOG_DEBUG("[id:" << getId() << ",endpoint:" << m_interfaceName
                     << "] Falling back to promiscuous mode");
-      pcap_set_promisc(m_pcap, 1);
+      pcap_set_promisc(m_pcap.get(), 1);
     }
 }
 
@@ -253,8 +254,7 @@
     {
       NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
                    << "] Trying to send on closed face");
-      fail("Face closed");
-      return;
+      return fail("Face closed");
     }
 
   /// \todo Fragmentation
@@ -283,14 +283,14 @@
   buffer.prependByteArray(m_destAddress.data(), m_destAddress.size());
 
   // send the packet
-  int sent = pcap_inject(m_pcap, buffer.buf(), buffer.size());
+  int sent = pcap_inject(m_pcap.get(), buffer.buf(), buffer.size());
   if (sent < 0)
     {
-      throw Error("pcap_inject(): " + std::string(pcap_geterr(m_pcap)));
+      return fail("pcap_inject(): " + std::string(pcap_geterr(m_pcap.get())));
     }
   else if (static_cast<size_t>(sent) < buffer.size())
     {
-      throw Error("Failed to send packet");
+      return fail("Failed to inject frame");
     }
 
   NFD_LOG_TRACE("[id:" << getId() << ",endpoint:" << m_interfaceName
@@ -301,56 +301,26 @@
 void
 EthernetFace::handleRead(const boost::system::error_code& error, size_t)
 {
+  if (!m_pcap)
+    return fail("Face closed");
+
   if (error)
     return processErrorCode(error);
 
-  pcap_pkthdr* pktHeader;
+  pcap_pkthdr* header;
   const uint8_t* packet;
-  int ret = pcap_next_ex(m_pcap, &pktHeader, &packet);
+  int ret = pcap_next_ex(m_pcap.get(), &header, &packet);
   if (ret < 0)
     {
-      throw Error("pcap_next_ex(): " + std::string(pcap_geterr(m_pcap)));
+      return fail("pcap_next_ex(): " + std::string(pcap_geterr(m_pcap.get())));
     }
   else if (ret == 0)
     {
-      NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
-                   << "] pcap_next_ex() timed out");
+      NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName << "] Read timeout");
     }
   else
     {
-      size_t length = pktHeader->caplen;
-      if (length < ethernet::HDR_LEN + ethernet::MIN_DATA_LEN)
-        throw Error("Received packet is too short");
-
-      const ether_header* eh = reinterpret_cast<const ether_header*>(packet);
-      if (ntohs(eh->ether_type) != ethernet::ETHERTYPE_NDN)
-        throw Error("Unrecognized ethertype");
-
-      packet += ethernet::HDR_LEN;
-      length -= ethernet::HDR_LEN;
-
-      /// \todo Reserve space in front and at the back
-      ///       of the underlying buffer
-      Block element;
-      bool isOk = Block::fromBuffer(packet, length, element);
-      if (isOk)
-        {
-          NFD_LOG_TRACE("[id:" << getId() << ",endpoint:" << m_interfaceName
-                        << "] Received: " << element.size() << " bytes");
-          this->getMutableCounters().getNInBytes() += element.size();
-
-          if (!decodeAndDispatchInput(element))
-            {
-              NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
-                           << "] Received unrecognized block of type " << element.type());
-              // ignore unknown packet
-            }
-        }
-      else
-        {
-          NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
-                       << "] Received block is invalid or too large to process");
-        }
+      processIncomingPacket(header, packet);
     }
 
   m_socket->async_read_some(boost::asio::null_buffers(),
@@ -360,18 +330,58 @@
 }
 
 void
-EthernetFace::processErrorCode(const boost::system::error_code& error)
+EthernetFace::processIncomingPacket(const pcap_pkthdr* header, const uint8_t* packet)
 {
-  if (error == boost::system::errc::operation_canceled)
-    // when socket is closed by someone
-    return;
-
-  if (!m_pcap)
+  size_t length = header->caplen;
+  if (length < ethernet::HDR_LEN + ethernet::MIN_DATA_LEN)
     {
-      fail("Face closed");
+      NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
+                   << "] Received frame is too short (" << length << " bytes)");
       return;
     }
 
+  const ether_header* eh = reinterpret_cast<const ether_header*>(packet);
+
+  // assert in case BPF fails to filter unwanted frames
+  BOOST_ASSERT_MSG(ethernet::Address(eh->ether_dhost) == m_destAddress,
+                   "Received frame addressed to a different multicast group");
+  BOOST_ASSERT_MSG(ethernet::Address(eh->ether_shost) != m_srcAddress,
+                   "Received frame sent by this host");
+  BOOST_ASSERT_MSG(ntohs(eh->ether_type) == ethernet::ETHERTYPE_NDN,
+                   "Received frame with unrecognized ethertype");
+
+  packet += ethernet::HDR_LEN;
+  length -= ethernet::HDR_LEN;
+
+  /// \todo Reserve space in front and at the back of the underlying buffer
+  Block element;
+  bool isOk = Block::fromBuffer(packet, length, element);
+  if (isOk)
+    {
+      NFD_LOG_TRACE("[id:" << getId() << ",endpoint:" << m_interfaceName
+                    << "] Received: " << element.size() << " bytes");
+      this->getMutableCounters().getNInBytes() += element.size();
+
+      if (!decodeAndDispatchInput(element))
+        {
+          NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
+                       << "] Received unrecognized block of type " << element.type());
+        }
+    }
+  else
+    {
+      NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
+                   << "] Received block is invalid or too large to process");
+    }
+}
+
+void
+EthernetFace::processErrorCode(const boost::system::error_code& error)
+{
+  if (error == boost::asio::error::operation_aborted)
+    // cancel() has been called on the socket
+    return;
+
   std::string msg;
   if (error == boost::asio::error::eof)
     {
@@ -380,11 +390,9 @@
     }
   else
     {
-      msg = "Receive operation failed, closing face: " + error.message();
+      msg = "Receive operation failed: " + error.message();
       NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName << "] " << msg);
     }
-
-  close();
   fail(msg);
 }
 
diff --git a/daemon/face/ethernet-face.hpp b/daemon/face/ethernet-face.hpp
index 0c673c3..1dd6593 100644
--- a/daemon/face/ethernet-face.hpp
+++ b/daemon/face/ethernet-face.hpp
@@ -26,7 +26,7 @@
 #ifndef NFD_DAEMON_FACE_ETHERNET_FACE_HPP
 #define NFD_DAEMON_FACE_ETHERNET_FACE_HPP
 
-#include "config.hpp"
+#include "common.hpp"
 #include "face.hpp"
 #include "core/network-interface.hpp"
 
@@ -37,18 +37,19 @@
 // forward declarations
 struct pcap;
 typedef pcap pcap_t;
+struct pcap_pkthdr;
 
 namespace nfd {
 
 /**
- * \brief Implementation of Face abstraction that uses raw
+ * @brief Implementation of Face abstraction that uses raw
  *        Ethernet frames as underlying transport mechanism
  */
 class EthernetFace : public Face
 {
 public:
   /**
-   * \brief EthernetFace-related error
+   * @brief EthernetFace-related error
    */
   struct Error : public Face::Error
   {
@@ -71,39 +72,73 @@
   sendData(const Data& data);
 
   /**
-   * \brief Close the face
+   * @brief Closes the face
    *
-   * This terminates all communication on the face and cause
-   * onFail() method event to be invoked
+   * This terminates all communication on the face and triggers the onFail() event.
    */
   virtual void
   close();
 
 private:
+  /**
+   * @brief Allocates and initializes a libpcap context for live capture
+   */
   void
   pcapInit();
 
+  /**
+   * @brief Installs a BPF filter on the receiving socket
+   *
+   * @param filterString string containing the source BPF program
+   */
   void
   setPacketFilter(const char* filterString);
 
+  /**
+   * @brief Enables receiving frames addressed to our MAC multicast group
+   */
   void
   joinMulticastGroup();
 
+  /**
+   * @brief Sends the specified TLV block on the network wrapped in an Ethernet frame
+   */
   void
   sendPacket(const ndn::Block& block);
 
+  /**
+   * @brief Receive callback
+   */
   void
-  handleRead(const boost::system::error_code& error,
-             size_t nBytesRead);
+  handleRead(const boost::system::error_code& error, size_t nBytesRead);
 
+PUBLIC_WITH_TESTS_ELSE_PRIVATE:
+  /**
+   * @brief Processes an incoming frame as captured by libpcap
+   *
+   * @param header pointer to capture metadata
+   * @param packet pointer to the received frame, including the link-layer header
+   */
+  void
+  processIncomingPacket(const pcap_pkthdr* header, const uint8_t* packet);
+
+private:
+  /**
+   * @brief Handles errors encountered by Boost.Asio on the receive path
+   */
   void
   processErrorCode(const boost::system::error_code& error);
 
+  /**
+   * @brief Returns the MTU of the underlying network interface
+   */
   size_t
   getInterfaceMtu() const;
 
 private:
+  unique_ptr<pcap_t, void(*)(pcap_t*)> m_pcap;
   shared_ptr<boost::asio::posix::stream_descriptor> m_socket;
+
 #if defined(__linux__)
   int m_interfaceIndex;
 #endif
@@ -111,7 +146,6 @@
   ethernet::Address m_srcAddress;
   ethernet::Address m_destAddress;
   size_t m_interfaceMtu;
-  pcap_t* m_pcap;
 };
 
 } // namespace nfd
diff --git a/daemon/face/ethernet-factory.cpp b/daemon/face/ethernet-factory.cpp
index 314614e..d9f1612 100644
--- a/daemon/face/ethernet-factory.cpp
+++ b/daemon/face/ethernet-factory.cpp
@@ -27,9 +27,6 @@
 #include "core/logger.hpp"
 #include "core/global-io.hpp"
 
-#include <boost/algorithm/string/predicate.hpp>
-#include <pcap/pcap.h>
-
 namespace nfd {
 
 NFD_LOG_INIT("EthernetFactory");
@@ -45,35 +42,27 @@
   if (face)
     return face;
 
-  shared_ptr<boost::asio::posix::stream_descriptor> socket =
-    make_shared<boost::asio::posix::stream_descriptor>(ref(getGlobalIoService()));
-
+  auto socket = make_shared<boost::asio::posix::stream_descriptor>(ref(getGlobalIoService()));
   face = make_shared<EthernetFace>(socket, interface, address);
-  face->onFail += bind(&EthernetFactory::afterFaceFailed,
-                       this, interface.name, address);
-  m_multicastFaces[std::make_pair(interface.name, address)] = face;
+
+  auto key = std::make_pair(interface.name, address);
+  face->onFail += [this, key] (const std::string& reason) {
+    m_multicastFaces.erase(key);
+  };
+  m_multicastFaces.insert({key, face});
 
   return face;
 }
 
-void
-EthernetFactory::afterFaceFailed(const std::string& interfaceName,
-                                 const ethernet::Address& address)
-{
-  NFD_LOG_DEBUG("afterFaceFailed: " << interfaceName << "/" << address);
-  m_multicastFaces.erase(std::make_pair(interfaceName, address));
-}
-
 shared_ptr<EthernetFace>
 EthernetFactory::findMulticastFace(const std::string& interfaceName,
                                    const ethernet::Address& address) const
 {
-  MulticastFaceMap::const_iterator i =
-    m_multicastFaces.find(std::make_pair(interfaceName, address));
-  if (i != m_multicastFaces.end())
-    return i->second;
+  auto it = m_multicastFaces.find({interfaceName, address});
+  if (it != m_multicastFaces.end())
+    return it->second;
   else
-    return shared_ptr<EthernetFace>();
+    return {};
 }
 
 void
@@ -84,10 +73,10 @@
   throw Error("EthernetFactory does not support 'createFace' operation");
 }
 
-std::list<shared_ptr<const Channel> >
+std::list<shared_ptr<const Channel>>
 EthernetFactory::getChannels() const
 {
-  return std::list<shared_ptr<const Channel> >();
+  return {};
 }
 
 } // namespace nfd
diff --git a/daemon/face/ethernet-factory.hpp b/daemon/face/ethernet-factory.hpp
index b7d5ec0..cc8516a 100644
--- a/daemon/face/ethernet-factory.hpp
+++ b/daemon/face/ethernet-factory.hpp
@@ -47,8 +47,8 @@
     }
   };
 
-  typedef std::map< std::pair<std::string, ethernet::Address>,
-                    shared_ptr<EthernetFace> > MulticastFaceMap;
+  typedef std::map<std::pair<std::string, ethernet::Address>,
+                   shared_ptr<EthernetFace>> MulticastFaceMap;
 
   // from ProtocolFactory
   virtual void
@@ -81,14 +81,10 @@
   const MulticastFaceMap&
   getMulticastFaces() const;
 
-  virtual std::list<shared_ptr<const Channel> >
+  virtual std::list<shared_ptr<const Channel>>
   getChannels() const;
 
 private:
-  void
-  afterFaceFailed(const std::string& interfaceName,
-                  const ethernet::Address& address);
-
   /**
    * \brief Look up EthernetFace using specified interface and address
    *
@@ -105,14 +101,12 @@
   MulticastFaceMap m_multicastFaces;
 };
 
-
 inline const EthernetFactory::MulticastFaceMap&
 EthernetFactory::getMulticastFaces() const
 {
   return m_multicastFaces;
 }
 
-
 } // namespace nfd
 
 #endif // NFD_DAEMON_FACE_ETHERNET_FACTORY_HPP
diff --git a/tests/daemon/face/ethernet.cpp b/tests/daemon/face/ethernet.cpp
index 2f872f1..54cca5d 100644
--- a/tests/daemon/face/ethernet.cpp
+++ b/tests/daemon/face/ethernet.cpp
@@ -23,24 +23,17 @@
  * NFD, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
  */
 
+#include "face/ethernet-face.hpp"
 #include "face/ethernet-factory.hpp"
-#include "core/network-interface.hpp"
 
+#include "core/network-interface.hpp"
 #include "tests/test-common.hpp"
 
+#include <pcap/pcap.h>
+
 namespace nfd {
 namespace tests {
 
-BOOST_FIXTURE_TEST_SUITE(FaceEthernet, BaseFixture)
-
-BOOST_AUTO_TEST_CASE(GetChannels)
-{
-  EthernetFactory factory;
-
-  auto channels = factory.getChannels();
-  BOOST_CHECK_EQUAL(channels.empty(), true);
-}
-
 class InterfacesFixture : protected BaseFixture
 {
 protected:
@@ -66,17 +59,25 @@
   std::vector<NetworkInterfaceInfo> m_interfaces;
 };
 
+BOOST_FIXTURE_TEST_SUITE(FaceEthernet, InterfacesFixture)
 
-BOOST_FIXTURE_TEST_CASE(MulticastFacesMap, InterfacesFixture)
+BOOST_AUTO_TEST_CASE(GetChannels)
 {
   EthernetFactory factory;
 
-  if (m_interfaces.empty())
-    {
-      BOOST_WARN_MESSAGE(false, "No interfaces available, cannot perform MulticastFacesMap test");
-      return;
-    }
+  auto channels = factory.getChannels();
+  BOOST_CHECK_EQUAL(channels.empty(), true);
+}
 
+BOOST_AUTO_TEST_CASE(MulticastFacesMap)
+{
+  if (m_interfaces.empty()) {
+    BOOST_WARN_MESSAGE(false, "No interfaces available for pcap, "
+                              "cannot perform MulticastFacesMap test");
+    return;
+  }
+
+  EthernetFactory factory;
   shared_ptr<EthernetFace> face1 = factory.createMulticastFace(m_interfaces.front(),
                                                                ethernet::getBroadcastAddress());
   shared_ptr<EthernetFace> face1bis = factory.createMulticastFace(m_interfaces.front(),
@@ -89,8 +90,8 @@
     BOOST_CHECK_NE(face1, face2);
   }
   else {
-    BOOST_WARN_MESSAGE(false, "Cannot test second EthernetFace creation, "
-                       "only one interface available");
+    BOOST_WARN_MESSAGE(false, "Only one interface available for pcap, "
+                              "cannot test second EthernetFace creation");
   }
 
   shared_ptr<EthernetFace> face3 = factory.createMulticastFace(m_interfaces.front(),
@@ -98,36 +99,44 @@
   BOOST_CHECK_NE(face1, face3);
 }
 
-BOOST_FIXTURE_TEST_CASE(SendPacket, InterfacesFixture)
+BOOST_AUTO_TEST_CASE(SendPacket)
 {
+  if (m_interfaces.empty()) {
+    BOOST_WARN_MESSAGE(false, "No interfaces available for pcap, "
+                              "cannot perform SendPacket test");
+    return;
+  }
+
   EthernetFactory factory;
-
-  if (m_interfaces.empty())
-    {
-      BOOST_WARN_MESSAGE(false, "No interfaces available for pcap, cannot perform SendPacket test");
-      return;
-    }
-
   shared_ptr<EthernetFace> face = factory.createMulticastFace(m_interfaces.front(),
                                     ethernet::getDefaultMulticastAddress());
-  BOOST_REQUIRE(static_cast<bool>(face));
 
-  BOOST_CHECK(!face->isOnDemand());
+  BOOST_REQUIRE(static_cast<bool>(face));
   BOOST_CHECK_EQUAL(face->isLocal(), false);
+  BOOST_CHECK_EQUAL(face->isOnDemand(), false);
   BOOST_CHECK_EQUAL(face->getRemoteUri().toString(),
                     "ether://[" + ethernet::getDefaultMulticastAddress().toString() + "]");
   BOOST_CHECK_EQUAL(face->getLocalUri().toString(),
                     "dev://" + m_interfaces.front().name);
+  BOOST_CHECK_EQUAL(face->getCounters().getNInBytes(), 0);
+  BOOST_CHECK_EQUAL(face->getCounters().getNOutBytes(), 0);
+
+  face->onFail += [] (const std::string& reason) { BOOST_FAIL(reason); };
 
   shared_ptr<Interest> interest1 = makeInterest("ndn:/TpnzGvW9R");
   shared_ptr<Data>     data1     = makeData("ndn:/KfczhUqVix");
   shared_ptr<Interest> interest2 = makeInterest("ndn:/QWiIMfj5sL");
   shared_ptr<Data>     data2     = makeData("ndn:/XNBV796f");
 
-  BOOST_CHECK_NO_THROW(face->sendInterest(*interest1));
-  BOOST_CHECK_NO_THROW(face->sendData    (*data1    ));
-  BOOST_CHECK_NO_THROW(face->sendInterest(*interest2));
-  BOOST_CHECK_NO_THROW(face->sendData    (*data2    ));
+  face->sendInterest(*interest1);
+  face->sendData    (*data1    );
+  face->sendInterest(*interest2);
+  face->sendData    (*data2    );
+
+  BOOST_CHECK_EQUAL(face->getCounters().getNOutBytes(), interest1->wireEncode().size() +
+                                                        data1->wireEncode().size() +
+                                                        interest2->wireEncode().size() +
+                                                        data2->wireEncode().size());
 
 //  m_ioRemaining = 4;
 //  m_ioService.run();
@@ -144,6 +153,88 @@
 //  BOOST_CHECK_EQUAL(m_face2_receivedDatas    [0].getName(), data1.getName());
 }
 
+BOOST_AUTO_TEST_CASE(ProcessIncomingPacket)
+{
+  if (m_interfaces.empty()) {
+    BOOST_WARN_MESSAGE(false, "No interfaces available for pcap, "
+                              "cannot perform ProcessIncomingPacket test");
+    return;
+  }
+
+  EthernetFactory factory;
+  shared_ptr<EthernetFace> face = factory.createMulticastFace(m_interfaces.front(),
+                                    ethernet::getDefaultMulticastAddress());
+  BOOST_REQUIRE(static_cast<bool>(face));
+
+  std::vector<Interest> recInterests;
+  std::vector<Data>     recDatas;
+
+  face->onFail            += [] (const std::string& reason) { BOOST_FAIL(reason); };
+  face->onReceiveInterest += [&recInterests] (const Interest& i) { recInterests.push_back(i); };
+  face->onReceiveData     += [&recDatas]     (const Data& d)     { recDatas.push_back(d);     };
+
+  // check that packet data is not accessed if pcap didn't capture anything (caplen == 0)
+  static const pcap_pkthdr header1{};
+  face->processIncomingPacket(&header1, nullptr);
+  BOOST_CHECK_EQUAL(face->getCounters().getNInBytes(), 0);
+  BOOST_CHECK_EQUAL(recInterests.size(), 0);
+  BOOST_CHECK_EQUAL(recDatas.size(), 0);
+
+  // runt frame (too short)
+  static const pcap_pkthdr header2{{}, ethernet::HDR_LEN + 6};
+  static const uint8_t packet2[ethernet::HDR_LEN + 6]{};
+  face->processIncomingPacket(&header2, packet2);
+  BOOST_CHECK_EQUAL(face->getCounters().getNInBytes(), 0);
+  BOOST_CHECK_EQUAL(recInterests.size(), 0);
+  BOOST_CHECK_EQUAL(recDatas.size(), 0);
+
+  // valid frame, but TLV block has invalid length
+  static const pcap_pkthdr header3{{}, ethernet::HDR_LEN + ethernet::MIN_DATA_LEN};
+  static const uint8_t packet3[ethernet::HDR_LEN + ethernet::MIN_DATA_LEN]{
+    0x01, 0x00, 0x5E, 0x00, 0x17, 0xAA, // destination address
+    0x02, 0x00, 0x00, 0x00, 0x00, 0x02, // source address
+    0x86, 0x24,       // NDN ethertype
+    tlv::Data,        // TLV type
+    0xFD, 0xFF, 0xFF  // TLV length (invalid because greater than packet size)
+  };
+  face->processIncomingPacket(&header3, packet3);
+  BOOST_CHECK_EQUAL(face->getCounters().getNInBytes(), 0);
+  BOOST_CHECK_EQUAL(recInterests.size(), 0);
+  BOOST_CHECK_EQUAL(recDatas.size(), 0);
+
+  // valid frame, but TLV block has invalid type
+  static const pcap_pkthdr header4{{}, ethernet::HDR_LEN + ethernet::MIN_DATA_LEN};
+  static const uint8_t packet4[ethernet::HDR_LEN + ethernet::MIN_DATA_LEN]{
+    0x01, 0x00, 0x5E, 0x00, 0x17, 0xAA, // destination address
+    0x02, 0x00, 0x00, 0x00, 0x00, 0x02, // source address
+    0x86, 0x24,       // NDN ethertype
+    0x00,             // TLV type (invalid)
+    0x00              // TLV length
+  };
+  face->processIncomingPacket(&header4, packet4);
+  BOOST_CHECK_EQUAL(face->getCounters().getNInBytes(), 2);
+  BOOST_CHECK_EQUAL(recInterests.size(), 0);
+  BOOST_CHECK_EQUAL(recDatas.size(), 0);
+
+  // valid frame and valid TLV block
+  static const pcap_pkthdr header5{{}, ethernet::HDR_LEN + ethernet::MIN_DATA_LEN};
+  static const uint8_t packet5[ethernet::HDR_LEN + ethernet::MIN_DATA_LEN]{
+    0x01, 0x00, 0x5E, 0x00, 0x17, 0xAA, // destination address
+    0x02, 0x00, 0x00, 0x00, 0x00, 0x02, // source address
+    0x86, 0x24,       // NDN ethertype
+    tlv::Interest,    // TLV type
+    0x16,             // TLV length
+    0x07, 0x0e, 0x08, 0x07, 0x65, 0x78, // payload
+    0x61, 0x6d, 0x70, 0x6c, 0x65, 0x08,
+    0x03, 0x66, 0x6f, 0x6f, 0x0a, 0x04,
+    0x03, 0xef, 0xe9, 0x7c
+  };
+  face->processIncomingPacket(&header5, packet5);
+  BOOST_CHECK_EQUAL(face->getCounters().getNInBytes(), 26);
+  BOOST_CHECK_EQUAL(recInterests.size(), 1);
+  BOOST_CHECK_EQUAL(recDatas.size(), 0);
+}
+
 BOOST_AUTO_TEST_SUITE_END()
 
 } // namespace tests