face: introduce PcapHelper class

Change-Id: I26f7d43394e1b17f314c226ca6bce723c2410ae3
Refs: #4011
diff --git a/daemon/face/ethernet-transport.cpp b/daemon/face/ethernet-transport.cpp
index be44e0c..0773e85 100644
--- a/daemon/face/ethernet-transport.cpp
+++ b/daemon/face/ethernet-transport.cpp
@@ -34,11 +34,6 @@
 #include <net/ethernet.h> // for struct ether_header
 #include <net/if.h>       // for struct ifreq
 #include <sys/ioctl.h>    // for ioctl()
-#include <unistd.h>       // for dup()
-
-#if !defined(PCAP_NETMASK_UNKNOWN)
-#define PCAP_NETMASK_UNKNOWN  0xffffffff
-#endif
 
 namespace nfd {
 namespace face {
@@ -47,28 +42,22 @@
 
 EthernetTransport::EthernetTransport(const NetworkInterfaceInfo& localEndpoint,
                                      const ethernet::Address& remoteEndpoint)
-  : m_pcap(nullptr, pcap_close)
-  , m_socket(getGlobalIoService())
+  : m_socket(getGlobalIoService())
+  , m_pcap(localEndpoint.name)
   , m_srcAddress(localEndpoint.etherAddress)
   , m_destAddress(remoteEndpoint)
   , m_interfaceName(localEndpoint.name)
-#if defined(__linux__)
-  , m_interfaceIndex(localEndpoint.index)
-#endif
 #ifdef _DEBUG
   , m_nDropped(0)
 #endif
 {
-  pcapInit();
-
-  int fd = pcap_get_selectable_fd(m_pcap.get());
-  if (fd < 0)
-    BOOST_THROW_EXCEPTION(Error("pcap_get_selectable_fd failed"));
-
-  // need to duplicate the fd, otherwise both pcap_close()
-  // and stream_descriptor::close() will try to close the
-  // same fd and one of them will fail
-  m_socket.assign(::dup(fd));
+  try {
+    m_pcap.activate(DLT_EN10MB);
+    m_socket.assign(m_pcap.getFd());
+  }
+  catch (const PcapHelper::Error& e) {
+    BOOST_THROW_EXCEPTION(Error(e.what()));
+  }
 
   // do this after assigning m_socket because getInterfaceMtu uses it
   this->setMtu(getInterfaceMtu());
@@ -80,14 +69,6 @@
 }
 
 void
-EthernetTransport::doSend(Transport::Packet&& packet)
-{
-  NFD_LOG_FACE_TRACE(__func__);
-
-  sendPacket(packet.packet);
-}
-
-void
 EthernetTransport::doClose()
 {
   NFD_LOG_FACE_TRACE(__func__);
@@ -99,7 +80,7 @@
     m_socket.cancel(error);
     m_socket.close(error);
   }
-  m_pcap.reset();
+  m_pcap.close();
 
   // Ensure that the Transport stays alive at least
   // until all pending handlers are dispatched
@@ -109,50 +90,16 @@
 }
 
 void
-EthernetTransport::pcapInit()
+EthernetTransport::doSend(Transport::Packet&& packet)
 {
-  char errbuf[PCAP_ERRBUF_SIZE] = {};
-  m_pcap.reset(pcap_create(m_interfaceName.c_str(), errbuf));
-  if (!m_pcap)
-    BOOST_THROW_EXCEPTION(Error("pcap_create: " + std::string(errbuf)));
+  NFD_LOG_FACE_TRACE(__func__);
 
-#ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
-  // Enable "immediate mode", effectively disabling any read buffering in the kernel.
-  // This corresponds to the BIOCIMMEDIATE ioctl on BSD-like systems (including macOS)
-  // 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.get(), 1);
-#endif
-
-  if (pcap_activate(m_pcap.get()) < 0)
-    BOOST_THROW_EXCEPTION(Error("pcap_activate failed"));
-
-  if (pcap_set_datalink(m_pcap.get(), DLT_EN10MB) < 0)
-    BOOST_THROW_EXCEPTION(Error("pcap_set_datalink: " + std::string(pcap_geterr(m_pcap.get()))));
-
-  if (pcap_setdirection(m_pcap.get(), PCAP_D_IN) < 0)
-    // no need to throw on failure, BPF will filter unwanted packets anyway
-    NFD_LOG_FACE_WARN("pcap_setdirection failed: " << pcap_geterr(m_pcap.get()));
-}
-
-void
-EthernetTransport::setPacketFilter(const char* filterString)
-{
-  bpf_program filter;
-  if (pcap_compile(m_pcap.get(), &filter, filterString, 1, PCAP_NETMASK_UNKNOWN) < 0)
-    BOOST_THROW_EXCEPTION(Error("pcap_compile: " + std::string(pcap_geterr(m_pcap.get()))));
-
-  int ret = pcap_setfilter(m_pcap.get(), &filter);
-  pcap_freecode(&filter);
-  if (ret < 0)
-    BOOST_THROW_EXCEPTION(Error("pcap_setfilter: " + std::string(pcap_geterr(m_pcap.get()))));
+  sendPacket(packet.packet);
 }
 
 void
 EthernetTransport::sendPacket(const ndn::Block& block)
 {
-  /// \todo Right now there is no reserve when packet is received, but
-  ///       we should reserve some space at the beginning and at the end
   ndn::EncodingBuffer buffer(block);
 
   // pad with zeroes if the payload is too short
@@ -168,9 +115,9 @@
   buffer.prependByteArray(m_destAddress.data(), m_destAddress.size());
 
   // send the packet
-  int sent = pcap_inject(m_pcap.get(), buffer.buf(), buffer.size());
+  int sent = pcap_inject(m_pcap, buffer.buf(), buffer.size());
   if (sent < 0)
-    NFD_LOG_FACE_ERROR("pcap_inject failed: " << pcap_geterr(m_pcap.get()));
+    NFD_LOG_FACE_ERROR("pcap_inject failed: " << m_pcap.getLastError());
   else if (static_cast<size_t>(sent) < buffer.size())
     NFD_LOG_FACE_ERROR("Failed to send the full frame: bufsize=" << buffer.size() << " sent=" << sent);
   else
@@ -184,29 +131,21 @@
   if (error)
     return processErrorCode(error);
 
-  pcap_pkthdr* header;
-  const uint8_t* packet;
+  const uint8_t* pkt;
+  size_t len;
+  std::string err;
+  std::tie(pkt, len, err) = m_pcap.readNextPacket();
 
-  // read the pcap header and packet data
-  int ret = pcap_next_ex(m_pcap.get(), &header, &packet);
-  if (ret < 0)
-    NFD_LOG_FACE_ERROR("pcap_next_ex failed: " << pcap_geterr(m_pcap.get()));
-  else if (ret == 0)
-    NFD_LOG_FACE_WARN("Read timeout");
+  if (pkt == nullptr)
+    NFD_LOG_FACE_ERROR("Read error: " << err);
   else
-    processIncomingPacket(header, packet);
+    processIncomingPacket(pkt, len);
 
 #ifdef _DEBUG
-  pcap_stat ps{};
-  ret = pcap_stats(m_pcap.get(), &ps);
-  if (ret < 0) {
-    NFD_LOG_FACE_DEBUG("pcap_stats failed: " << pcap_geterr(m_pcap.get()));
-  }
-  else if (ret == 0) {
-    if (ps.ps_drop - m_nDropped > 0)
-      NFD_LOG_FACE_DEBUG("Detected " << ps.ps_drop - m_nDropped << " dropped packet(s)");
-    m_nDropped = ps.ps_drop;
-  }
+  size_t nDropped = m_pcap.getNDropped();
+  if (nDropped - m_nDropped > 0)
+    NFD_LOG_FACE_DEBUG("Detected " << nDropped - m_nDropped << " dropped packet(s)");
+  m_nDropped = nDropped;
 #endif
 
   m_socket.async_read_some(boost::asio::null_buffers(),
@@ -216,9 +155,8 @@
 }
 
 void
-EthernetTransport::processIncomingPacket(const pcap_pkthdr* header, const uint8_t* packet)
+EthernetTransport::processIncomingPacket(const uint8_t* packet, size_t length)
 {
-  size_t length = header->caplen;
   if (length < ethernet::HDR_LEN + ethernet::MIN_DATA_LEN) {
     NFD_LOG_FACE_WARN("Received frame is too short (" << length << " bytes)");
     return;
@@ -274,7 +212,7 @@
   NFD_LOG_FACE_WARN("Receive operation failed: " << error.message());
 }
 
-size_t
+int
 EthernetTransport::getInterfaceMtu()
 {
 #ifdef SIOCGIFMTU
@@ -288,11 +226,11 @@
 #endif
 
   ifreq ifr{};
-  std::strncpy(ifr.ifr_name, m_interfaceName.c_str(), sizeof(ifr.ifr_name) - 1);
+  std::strncpy(ifr.ifr_name, m_interfaceName.data(), sizeof(ifr.ifr_name) - 1);
 
   if (::ioctl(fd, SIOCGIFMTU, &ifr) == 0) {
     NFD_LOG_FACE_DEBUG("Interface MTU is " << ifr.ifr_mtu);
-    return static_cast<size_t>(ifr.ifr_mtu);
+    return ifr.ifr_mtu;
   }
 
   NFD_LOG_FACE_WARN("Failed to get interface MTU: " << std::strerror(errno));
diff --git a/daemon/face/ethernet-transport.hpp b/daemon/face/ethernet-transport.hpp
index 8164a33..57a7edc 100644
--- a/daemon/face/ethernet-transport.hpp
+++ b/daemon/face/ethernet-transport.hpp
@@ -26,19 +26,10 @@
 #ifndef NFD_DAEMON_FACE_ETHERNET_TRANSPORT_HPP
 #define NFD_DAEMON_FACE_ETHERNET_TRANSPORT_HPP
 
-#include "core/common.hpp"
+#include "pcap-helper.hpp"
 #include "transport.hpp"
 #include "core/network-interface.hpp"
 
-#ifndef HAVE_LIBPCAP
-#error "Cannot include this file when libpcap is not available"
-#endif
-
-// forward declarations
-struct pcap;
-typedef pcap pcap_t;
-struct pcap_pkthdr;
-
 namespace nfd {
 namespace face {
 
@@ -65,20 +56,7 @@
   void
   doClose() final;
 
-  /**
-   * @brief Installs a BPF filter on the receiving socket
-   * @param filterString string containing the BPF program source
-   */
-  void
-  setPacketFilter(const char* filterString);
-
 private:
-  /**
-   * @brief Allocates and initializes a libpcap context for live capture
-   */
-  void
-  pcapInit();
-
   void
   doSend(Transport::Packet&& packet) final;
 
@@ -89,22 +67,19 @@
   sendPacket(const ndn::Block& block);
 
   /**
-   * @brief Receive callback
+   * @brief async_read_some() callback
    */
   void
   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
+   * @brief Processes an incoming packet as captured by libpcap
+   * @param packet Pointer to the received packet, including the link-layer header
+   * @param length Packet length
    */
   void
-  processIncomingPacket(const pcap_pkthdr* header, const uint8_t* packet);
+  processIncomingPacket(const uint8_t* packet, size_t length);
 
-private:
   /**
    * @brief Handles errors encountered by Boost.Asio on the receive path
    */
@@ -114,24 +89,20 @@
   /**
    * @brief Returns the MTU of the underlying network interface
    */
-  size_t
+  int
   getInterfaceMtu();
 
 protected:
-  unique_ptr<pcap_t, void(*)(pcap_t*)> m_pcap;
   boost::asio::posix::stream_descriptor m_socket;
-
+  PcapHelper m_pcap;
   ethernet::Address m_srcAddress;
   ethernet::Address m_destAddress;
   std::string m_interfaceName;
-#if defined(__linux__)
-  int m_interfaceIndex;
-#endif
 
 private:
 #ifdef _DEBUG
   /// number of packets dropped by the kernel, as reported by libpcap
-  unsigned int m_nDropped;
+  size_t m_nDropped;
 #endif
 };
 
diff --git a/daemon/face/multicast-ethernet-transport.cpp b/daemon/face/multicast-ethernet-transport.cpp
index 7e7f343..9f1127c 100644
--- a/daemon/face/multicast-ethernet-transport.cpp
+++ b/daemon/face/multicast-ethernet-transport.cpp
@@ -54,6 +54,9 @@
                                                        const ethernet::Address& mcastAddress,
                                                        ndn::nfd::LinkType linkType)
   : EthernetTransport(localEndpoint, mcastAddress)
+#if defined(__linux__)
+  , m_interfaceIndex(localEndpoint.index)
+#endif
 {
   this->setLocalUri(FaceUri::fromDev(m_interfaceName));
   this->setRemoteUri(FaceUri(m_destAddress));
@@ -71,13 +74,13 @@
   snprintf(filter, sizeof(filter),
            "(ether proto 0x%x) && (ether dst %s) && (not ether src %s) && (not vlan)",
            ethernet::ETHERTYPE_NDN,
-           m_destAddress.toString().c_str(),
-           m_srcAddress.toString().c_str());
-  setPacketFilter(filter);
+           m_destAddress.toString().data(),
+           m_srcAddress.toString().data());
+  m_pcap.setPacketFilter(filter);
 
   if (!m_destAddress.isBroadcast() && !joinMulticastGroup()) {
     NFD_LOG_FACE_WARN("Falling back to promiscuous mode");
-    pcap_set_promisc(m_pcap.get(), 1);
+    pcap_set_promisc(m_pcap, 1);
   }
 }
 
@@ -100,7 +103,7 @@
 
 #if defined(SIOCADDMULTI)
   ifreq ifr{};
-  std::strncpy(ifr.ifr_name, m_interfaceName.c_str(), sizeof(ifr.ifr_name) - 1);
+  std::strncpy(ifr.ifr_name, m_interfaceName.data(), sizeof(ifr.ifr_name) - 1);
 
 #if defined(__APPLE__) || defined(__FreeBSD__)
   // see bug #2327
diff --git a/daemon/face/multicast-ethernet-transport.hpp b/daemon/face/multicast-ethernet-transport.hpp
index 6d25b41..6ef893b 100644
--- a/daemon/face/multicast-ethernet-transport.hpp
+++ b/daemon/face/multicast-ethernet-transport.hpp
@@ -51,6 +51,11 @@
    */
   bool
   joinMulticastGroup();
+
+private:
+#if defined(__linux__)
+  int m_interfaceIndex;
+#endif
 };
 
 } // namespace face
diff --git a/daemon/face/pcap-helper.cpp b/daemon/face/pcap-helper.cpp
new file mode 100644
index 0000000..b1e57eb
--- /dev/null
+++ b/daemon/face/pcap-helper.cpp
@@ -0,0 +1,141 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014-2017,  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 "pcap-helper.hpp"
+
+#include <pcap/pcap.h>
+#include <unistd.h>
+
+#if !defined(PCAP_NETMASK_UNKNOWN)
+#define PCAP_NETMASK_UNKNOWN  0xffffffff
+#endif
+
+namespace nfd {
+namespace face {
+
+PcapHelper::PcapHelper(const std::string& interfaceName)
+  : m_pcap(nullptr)
+{
+  char errbuf[PCAP_ERRBUF_SIZE] = {};
+  m_pcap = pcap_create(interfaceName.data(), errbuf);
+  if (!m_pcap)
+    BOOST_THROW_EXCEPTION(Error("pcap_create: " + std::string(errbuf)));
+
+#ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
+  // Enable "immediate mode", effectively disabling any read buffering in the kernel.
+  // This corresponds to the BIOCIMMEDIATE ioctl on BSD-like systems (including macOS)
+  // 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.
+  if (pcap_set_immediate_mode(m_pcap, 1) < 0)
+    BOOST_THROW_EXCEPTION(Error("pcap_set_immediate_mode failed"));
+#endif
+}
+
+PcapHelper::~PcapHelper()
+{
+  close();
+}
+
+void
+PcapHelper::activate(int dlt)
+{
+  int ret = pcap_activate(m_pcap);
+  if (ret < 0)
+    BOOST_THROW_EXCEPTION(Error("pcap_activate: " + std::string(pcap_statustostr(ret))));
+
+  if (pcap_set_datalink(m_pcap, dlt) < 0)
+    BOOST_THROW_EXCEPTION(Error("pcap_set_datalink: " + getLastError()));
+
+  if (pcap_setdirection(m_pcap, PCAP_D_IN) < 0)
+    BOOST_THROW_EXCEPTION(Error("pcap_setdirection: " + getLastError()));
+}
+
+void
+PcapHelper::close()
+{
+  if (m_pcap) {
+    pcap_close(m_pcap);
+    m_pcap = nullptr;
+  }
+}
+
+int
+PcapHelper::getFd() const
+{
+  int fd = pcap_get_selectable_fd(m_pcap);
+  if (fd < 0)
+    BOOST_THROW_EXCEPTION(Error("pcap_get_selectable_fd failed"));
+
+  // we need to duplicate the fd, otherwise both pcap_close() and the
+  // caller may attempt to close the same fd and one of them will fail
+  return ::dup(fd);
+}
+
+std::string
+PcapHelper::getLastError() const
+{
+  return pcap_geterr(m_pcap);
+}
+
+size_t
+PcapHelper::getNDropped() const
+{
+  pcap_stat ps{};
+  if (pcap_stats(m_pcap, &ps) < 0)
+    BOOST_THROW_EXCEPTION(Error("pcap_stats: " + getLastError()));
+
+  return ps.ps_drop;
+}
+
+void
+PcapHelper::setPacketFilter(const char* filter) const
+{
+  bpf_program prog;
+  if (pcap_compile(m_pcap, &prog, filter, 1, PCAP_NETMASK_UNKNOWN) < 0)
+    BOOST_THROW_EXCEPTION(Error("pcap_compile: " + getLastError()));
+
+  int ret = pcap_setfilter(m_pcap, &prog);
+  pcap_freecode(&prog);
+  if (ret < 0)
+    BOOST_THROW_EXCEPTION(Error("pcap_setfilter: " + getLastError()));
+}
+
+std::tuple<const uint8_t*, size_t, std::string>
+PcapHelper::readNextPacket() const
+{
+  pcap_pkthdr* header;
+  const uint8_t* packet;
+
+  int ret = pcap_next_ex(m_pcap, &header, &packet);
+  if (ret < 0)
+    return std::make_tuple(nullptr, 0, getLastError());
+  else if (ret == 0)
+    return std::make_tuple(nullptr, 0, "timed out");
+  else
+    return std::make_tuple(packet, header->caplen, "");
+}
+
+} // namespace face
+} // namespace nfd
diff --git a/daemon/face/pcap-helper.hpp b/daemon/face/pcap-helper.hpp
new file mode 100644
index 0000000..5d239ce
--- /dev/null
+++ b/daemon/face/pcap-helper.hpp
@@ -0,0 +1,146 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014-2017,  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_PCAP_HELPER_HPP
+#define NFD_DAEMON_FACE_PCAP_HELPER_HPP
+
+#include "core/common.hpp"
+
+#ifndef HAVE_LIBPCAP
+#error "Cannot include this file when libpcap is not available"
+#endif
+
+// forward declarations
+struct pcap;
+typedef pcap pcap_t;
+
+namespace nfd {
+namespace face {
+
+/**
+ * @brief Helper class for dealing with libpcap handles.
+ */
+class PcapHelper : noncopyable
+{
+public:
+  class Error : public std::runtime_error
+  {
+  public:
+    explicit
+    Error(const std::string& what)
+      : std::runtime_error(what)
+    {
+    }
+  };
+
+  /**
+   * @brief Create a libpcap context for live packet capture on a network interface.
+   * @throw Error on any error
+   * @sa pcap_create(3pcap)
+   */
+  explicit
+  PcapHelper(const std::string& interfaceName);
+
+  ~PcapHelper();
+
+  /**
+   * @brief Start capturing packets.
+   * @param dlt The link-layer header type to be used.
+   * @throw Error on any error
+   * @sa pcap_activate(3pcap), pcap_set_datalink(3pcap)
+   */
+  void
+  activate(int dlt);
+
+  /**
+   * @brief Stop capturing and close the handle.
+   * @sa pcap_close(3pcap)
+   */
+  void
+  close();
+
+  /**
+   * @brief Obtain a file descriptor that can be used in calls such as select(2) and poll(2).
+   * @pre activate() has been called.
+   * @return A selectable file descriptor. It is the caller's responsibility to close the fd.
+   * @throw Error on any error
+   * @sa pcap_get_selectable_fd(3pcap)
+   */
+  int
+  getFd() const;
+
+  /**
+   * @brief Get last error message.
+   * @return Human-readable explanation of the last libpcap error.
+   * @warning The behavior is undefined if no error occurred.
+   * @sa pcap_geterr(3pcap)
+   */
+  std::string
+  getLastError() const;
+
+  /**
+   * @brief Get the number of packets dropped by the kernel, as reported by libpcap.
+   * @throw Error on any error
+   * @sa pcap_stats(3pcap)
+   */
+  size_t
+  getNDropped() const;
+
+  /**
+   * @brief Install a BPF filter on the receiving socket.
+   * @param filter Null-terminated string containing the BPF program source.
+   * @pre activate() has been called.
+   * @throw Error on any error
+   * @sa pcap_setfilter(3pcap), pcap-filter(7)
+   */
+  void
+  setPacketFilter(const char* filter) const;
+
+  /**
+   * @brief Read the next packet captured on the interface.
+   * @return If successful, returns a tuple containing a pointer to the received packet
+   *         (including the link-layer header) and the size of the packet; the third
+   *         element must be ignored. On failure, returns a tuple containing nullptr,
+   *         0, and the reason for the failure.
+   * @warning The returned pointer must not be freed by the caller, and is valid only
+   *          until the next call to this function.
+   * @sa pcap_next_ex(3pcap)
+   */
+  std::tuple<const uint8_t*, size_t, std::string>
+  readNextPacket() const;
+
+  operator pcap_t*() const
+  {
+    return m_pcap;
+  }
+
+private:
+  pcap_t* m_pcap;
+};
+
+} // namespace face
+} // namespace nfd
+
+#endif // NFD_DAEMON_FACE_PCAP_HELPER_HPP
diff --git a/daemon/face/unicast-ethernet-transport.cpp b/daemon/face/unicast-ethernet-transport.cpp
index e21a793..eb34648 100644
--- a/daemon/face/unicast-ethernet-transport.cpp
+++ b/daemon/face/unicast-ethernet-transport.cpp
@@ -55,9 +55,9 @@
   snprintf(filter, sizeof(filter),
            "(ether proto 0x%x) && (ether src %s) && (ether dst %s) && (not vlan)",
            ethernet::ETHERTYPE_NDN,
-           m_destAddress.toString().c_str(),
-           m_srcAddress.toString().c_str());
-  setPacketFilter(filter);
+           m_destAddress.toString().data(),
+           m_srcAddress.toString().data());
+  m_pcap.setPacketFilter(filter);
 
   // TODO: implement close on idle and persistency change
 }
diff --git a/wscript b/wscript
index 9bb3e15..ace1e8e 100644
--- a/wscript
+++ b/wscript
@@ -201,7 +201,8 @@
         name='daemon-objects',
         features='cxx',
         source=bld.path.ant_glob(['daemon/**/*.cpp'],
-                                 excl=['daemon/face/ethernet-*.cpp',
+                                 excl=['daemon/face/*ethernet*.cpp',
+                                       'daemon/face/*pcap*.cpp',
                                        'daemon/face/unix-*.cpp',
                                        'daemon/face/websocket-*.cpp',
                                        'daemon/main.cpp']),
@@ -210,7 +211,8 @@
         export_includes='daemon')
 
     if bld.env['HAVE_LIBPCAP']:
-        nfd_objects.source += bld.path.ant_glob('daemon/face/ethernet-*.cpp')
+        nfd_objects.source += bld.path.ant_glob('daemon/face/*ethernet*.cpp')
+        nfd_objects.source += bld.path.ant_glob('daemon/face/*pcap*.cpp')
         nfd_objects.use += ' LIBPCAP'
 
     if bld.env['HAVE_UNIX_SOCKETS']: