ethernet-transport.cpp
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
26 #include "ethernet-transport.hpp"
27 #include "core/global-io.hpp"
28 
29 #include <pcap/pcap.h>
30 
31 #include <cerrno> // for errno
32 #include <cstring> // for memcpy(), strerror(), strncpy()
33 #include <arpa/inet.h> // for htons() and ntohs()
34 #include <net/ethernet.h> // for struct ether_header
35 #include <net/if.h> // for struct ifreq
36 #include <stdio.h> // for snprintf()
37 #include <sys/ioctl.h> // for ioctl()
38 #include <unistd.h> // for dup()
39 
40 #if defined(__linux__)
41 #include <netpacket/packet.h> // for struct packet_mreq
42 #include <sys/socket.h> // for setsockopt()
43 #endif
44 
45 #ifdef SIOCADDMULTI
46 #if defined(__APPLE__) || defined(__FreeBSD__)
47 #include <net/if_dl.h> // for struct sockaddr_dl
48 #endif
49 #endif
50 
51 #if !defined(PCAP_NETMASK_UNKNOWN)
52 /*
53  * Value to pass to pcap_compile() as the netmask if you don't know what
54  * the netmask is.
55  */
56 #define PCAP_NETMASK_UNKNOWN 0xffffffff
57 #endif
58 
59 namespace nfd {
60 namespace face {
61 
62 NFD_LOG_INIT("EthernetTransport");
63 
65  const ethernet::Address& mcastAddress)
66  : m_pcap(nullptr, pcap_close)
67  , m_socket(getGlobalIoService())
68  , m_srcAddress(interface.etherAddress)
69  , m_destAddress(mcastAddress)
70  , m_interfaceName(interface.name)
71 #if defined(__linux__)
72  , m_interfaceIndex(interface.index)
73 #endif
74 #ifdef _DEBUG
75  , m_nDropped(0)
76 #endif
77 {
78  this->setLocalUri(FaceUri::fromDev(interface.name));
79  this->setRemoteUri(FaceUri(mcastAddress));
80  this->setScope(ndn::nfd::FACE_SCOPE_NON_LOCAL);
81  this->setPersistency(ndn::nfd::FACE_PERSISTENCY_PERMANENT);
82  this->setLinkType(ndn::nfd::LINK_TYPE_MULTI_ACCESS);
83 
84  NFD_LOG_FACE_INFO("Creating transport");
85 
86  pcapInit();
87 
88  int fd = pcap_get_selectable_fd(m_pcap.get());
89  if (fd < 0)
90  BOOST_THROW_EXCEPTION(Error("pcap_get_selectable_fd failed"));
91 
92  // need to duplicate the fd, otherwise both pcap_close()
93  // and stream_descriptor::close() will try to close the
94  // same fd and one of them will fail
95  m_socket.assign(::dup(fd));
96 
97  // do this after assigning m_socket because getInterfaceMtu uses it
98  this->setMtu(getInterfaceMtu());
99 
100  char filter[110];
101  // note #1: we cannot use std::snprintf because it's not available
102  // on some platforms (see #2299)
103  // note #2: "not vlan" must appear last in the filter expression, or the
104  // rest of the filter won't work as intended (see pcap-filter(7))
105  snprintf(filter, sizeof(filter),
106  "(ether proto 0x%x) && (ether dst %s) && (not ether src %s) && (not vlan)",
107  ethernet::ETHERTYPE_NDN,
108  m_destAddress.toString().c_str(),
109  m_srcAddress.toString().c_str());
110  setPacketFilter(filter);
111 
112  if (!m_destAddress.isBroadcast() && !joinMulticastGroup()) {
113  NFD_LOG_FACE_WARN("Falling back to promiscuous mode");
114  pcap_set_promisc(m_pcap.get(), 1);
115  }
116 
117  m_socket.async_read_some(boost::asio::null_buffers(),
118  bind(&EthernetTransport::handleRead, this,
119  boost::asio::placeholders::error,
120  boost::asio::placeholders::bytes_transferred));
121 }
122 
123 void EthernetTransport::doSend(Transport::Packet&& packet)
124 {
125  NFD_LOG_FACE_TRACE(__func__);
126 
127  sendPacket(packet.packet);
128 }
129 
131 {
132  NFD_LOG_FACE_TRACE(__func__);
133 
134  if (m_socket.is_open()) {
135  // Cancel all outstanding operations and close the socket.
136  // Use the non-throwing variants and ignore errors, if any.
137  boost::system::error_code error;
138  m_socket.cancel(error);
139  m_socket.close(error);
140  }
141  m_pcap.reset();
142 
143  // Ensure that the Transport stays alive at least
144  // until all pending handlers are dispatched
145  getGlobalIoService().post([this] {
147  });
148 }
149 
150 void
151 EthernetTransport::pcapInit()
152 {
153  char errbuf[PCAP_ERRBUF_SIZE] = {};
154  m_pcap.reset(pcap_create(m_interfaceName.c_str(), errbuf));
155  if (!m_pcap)
156  BOOST_THROW_EXCEPTION(Error("pcap_create: " + std::string(errbuf)));
157 
158 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
159  // Enable "immediate mode", effectively disabling any read buffering in the kernel.
160  // This corresponds to the BIOCIMMEDIATE ioctl on BSD-like systems (including OS X)
161  // where libpcap uses a BPF device. On Linux this forces libpcap not to use TPACKET_V3,
162  // even if the kernel supports it, thus preventing bug #1511.
163  pcap_set_immediate_mode(m_pcap.get(), 1);
164 #endif
165 
166  if (pcap_activate(m_pcap.get()) < 0)
167  BOOST_THROW_EXCEPTION(Error("pcap_activate failed"));
168 
169  if (pcap_set_datalink(m_pcap.get(), DLT_EN10MB) < 0)
170  BOOST_THROW_EXCEPTION(Error("pcap_set_datalink: " + std::string(pcap_geterr(m_pcap.get()))));
171 
172  if (pcap_setdirection(m_pcap.get(), PCAP_D_IN) < 0)
173  // no need to throw on failure, BPF will filter unwanted packets anyway
174  NFD_LOG_FACE_WARN("pcap_setdirection failed: " << pcap_geterr(m_pcap.get()));
175 }
176 
177 void
178 EthernetTransport::setPacketFilter(const char* filterString)
179 {
180  bpf_program filter;
181  if (pcap_compile(m_pcap.get(), &filter, filterString, 1, PCAP_NETMASK_UNKNOWN) < 0)
182  BOOST_THROW_EXCEPTION(Error("pcap_compile: " + std::string(pcap_geterr(m_pcap.get()))));
183 
184  int ret = pcap_setfilter(m_pcap.get(), &filter);
185  pcap_freecode(&filter);
186  if (ret < 0)
187  BOOST_THROW_EXCEPTION(Error("pcap_setfilter: " + std::string(pcap_geterr(m_pcap.get()))));
188 }
189 
190 bool
191 EthernetTransport::joinMulticastGroup()
192 {
193 #if defined(__linux__)
194  packet_mreq mr{};
195  mr.mr_ifindex = m_interfaceIndex;
196  mr.mr_type = PACKET_MR_MULTICAST;
197  mr.mr_alen = m_destAddress.size();
198  std::memcpy(mr.mr_address, m_destAddress.data(), m_destAddress.size());
199 
200  if (::setsockopt(m_socket.native_handle(), SOL_PACKET,
201  PACKET_ADD_MEMBERSHIP, &mr, sizeof(mr)) == 0)
202  return true; // success
203 
204  NFD_LOG_FACE_WARN("setsockopt(PACKET_ADD_MEMBERSHIP) failed: " << std::strerror(errno));
205 #endif
206 
207 #if defined(SIOCADDMULTI)
208  ifreq ifr{};
209  std::strncpy(ifr.ifr_name, m_interfaceName.c_str(), sizeof(ifr.ifr_name) - 1);
210 
211 #if defined(__APPLE__) || defined(__FreeBSD__)
212  // see bug #2327
213  using boost::asio::ip::udp;
214  udp::socket sock(getGlobalIoService(), udp::v4());
215  int fd = sock.native_handle();
216 
217  /*
218  * Differences between Linux and the BSDs (including OS X):
219  * o BSD does not have ifr_hwaddr; use ifr_addr instead.
220  * o While OS X seems to accept both AF_LINK and AF_UNSPEC as the address
221  * family, FreeBSD explicitly requires AF_LINK, so we have to use AF_LINK
222  * and sockaddr_dl instead of the generic sockaddr structure.
223  * o BSD's sockaddr (and sockaddr_dl in particular) contains an additional
224  * field, sa_len (sdl_len), which must be set to the total length of the
225  * structure, including the length field itself.
226  * o We do not specify the interface name, thus sdl_nlen is left at 0 and
227  * LLADDR is effectively the same as sdl_data.
228  */
229  sockaddr_dl* sdl = reinterpret_cast<sockaddr_dl*>(&ifr.ifr_addr);
230  sdl->sdl_len = sizeof(ifr.ifr_addr);
231  sdl->sdl_family = AF_LINK;
232  sdl->sdl_alen = m_destAddress.size();
233  std::memcpy(LLADDR(sdl), m_destAddress.data(), m_destAddress.size());
234 
235  static_assert(sizeof(ifr.ifr_addr) >= offsetof(sockaddr_dl, sdl_data) + ethernet::ADDR_LEN,
236  "ifr_addr in struct ifreq is too small on this platform");
237 #else
238  int fd = m_socket.native_handle();
239 
240  ifr.ifr_hwaddr.sa_family = AF_UNSPEC;
241  std::memcpy(ifr.ifr_hwaddr.sa_data, m_destAddress.data(), m_destAddress.size());
242 
243  static_assert(sizeof(ifr.ifr_hwaddr.sa_data) >= ethernet::ADDR_LEN,
244  "ifr_hwaddr in struct ifreq is too small on this platform");
245 #endif
246 
247  if (::ioctl(fd, SIOCADDMULTI, &ifr) == 0)
248  return true; // success
249 
250  NFD_LOG_FACE_WARN("ioctl(SIOCADDMULTI) failed: " << std::strerror(errno));
251 #endif
252 
253  return false;
254 }
255 
256 void
257 EthernetTransport::sendPacket(const ndn::Block& block)
258 {
261  ndn::EncodingBuffer buffer(block);
262 
263  // pad with zeroes if the payload is too short
264  if (block.size() < ethernet::MIN_DATA_LEN) {
265  static const uint8_t padding[ethernet::MIN_DATA_LEN] = {};
266  buffer.appendByteArray(padding, ethernet::MIN_DATA_LEN - block.size());
267  }
268 
269  // construct and prepend the ethernet header
270  static uint16_t ethertype = htons(ethernet::ETHERTYPE_NDN);
271  buffer.prependByteArray(reinterpret_cast<const uint8_t*>(&ethertype), ethernet::TYPE_LEN);
272  buffer.prependByteArray(m_srcAddress.data(), m_srcAddress.size());
273  buffer.prependByteArray(m_destAddress.data(), m_destAddress.size());
274 
275  // send the packet
276  int sent = pcap_inject(m_pcap.get(), buffer.buf(), buffer.size());
277  if (sent < 0)
278  NFD_LOG_FACE_ERROR("pcap_inject failed: " << pcap_geterr(m_pcap.get()));
279  else if (static_cast<size_t>(sent) < buffer.size())
280  NFD_LOG_FACE_ERROR("Failed to send the full frame: bufsize=" << buffer.size() << " sent=" << sent);
281  else
282  // print block size because we don't want to count the padding in buffer
283  NFD_LOG_FACE_TRACE("Successfully sent: " << block.size() << " bytes");
284 }
285 
286 void
287 EthernetTransport::handleRead(const boost::system::error_code& error, size_t)
288 {
289  if (error)
290  return processErrorCode(error);
291 
292  pcap_pkthdr* header;
293  const uint8_t* packet;
294 
295  // read the pcap header and packet data
296  int ret = pcap_next_ex(m_pcap.get(), &header, &packet);
297  if (ret < 0)
298  NFD_LOG_FACE_ERROR("pcap_next_ex failed: " << pcap_geterr(m_pcap.get()));
299  else if (ret == 0)
300  NFD_LOG_FACE_WARN("Read timeout");
301  else
302  processIncomingPacket(header, packet);
303 
304 #ifdef _DEBUG
305  pcap_stat ps{};
306  ret = pcap_stats(m_pcap.get(), &ps);
307  if (ret < 0) {
308  NFD_LOG_FACE_DEBUG("pcap_stats failed: " << pcap_geterr(m_pcap.get()));
309  }
310  else if (ret == 0) {
311  if (ps.ps_drop - m_nDropped > 0)
312  NFD_LOG_FACE_DEBUG("Detected " << ps.ps_drop - m_nDropped << " dropped packet(s)");
313  m_nDropped = ps.ps_drop;
314  }
315 #endif
316 
317  m_socket.async_read_some(boost::asio::null_buffers(),
318  bind(&EthernetTransport::handleRead, this,
319  boost::asio::placeholders::error,
320  boost::asio::placeholders::bytes_transferred));
321 }
322 
323 void
324 EthernetTransport::processIncomingPacket(const pcap_pkthdr* header, const uint8_t* packet)
325 {
326  size_t length = header->caplen;
327  if (length < ethernet::HDR_LEN + ethernet::MIN_DATA_LEN) {
328  NFD_LOG_FACE_WARN("Received frame is too short (" << length << " bytes)");
329  return;
330  }
331 
332  const ether_header* eh = reinterpret_cast<const ether_header*>(packet);
333  const ethernet::Address sourceAddress(eh->ether_shost);
334 
335  // in some cases VLAN-tagged frames may survive the BPF filter,
336  // make sure we do not process those frames (see #3348)
337  if (ntohs(eh->ether_type) != ethernet::ETHERTYPE_NDN)
338  return;
339 
340  // check that our BPF filter is working correctly
341  BOOST_ASSERT_MSG(ethernet::Address(eh->ether_dhost) == m_destAddress,
342  "Received frame addressed to a different multicast group");
343  BOOST_ASSERT_MSG(sourceAddress != m_srcAddress,
344  "Received frame sent by this host");
345 
346  packet += ethernet::HDR_LEN;
347  length -= ethernet::HDR_LEN;
348 
349  bool isOk = false;
350  Block element;
351  std::tie(isOk, element) = Block::fromBuffer(packet, length);
352  if (!isOk) {
353  NFD_LOG_FACE_WARN("Received invalid packet from " << sourceAddress.toString());
354  return;
355  }
356 
357  NFD_LOG_FACE_TRACE("Received: " << element.size() << " bytes from " << sourceAddress.toString());
358 
359  Transport::Packet tp(std::move(element));
360  static_assert(sizeof(tp.remoteEndpoint) >= ethernet::ADDR_LEN,
361  "Transport::Packet::remoteEndpoint is too small");
362  std::memcpy(&tp.remoteEndpoint, sourceAddress.data(), sourceAddress.size());
363  this->receive(std::move(tp));
364 }
365 
366 void
367 EthernetTransport::processErrorCode(const boost::system::error_code& error)
368 {
369  // boost::asio::error::operation_aborted must be checked first. In that situation, the Transport
370  // may already have been destructed, and it's unsafe to call getState() or do logging.
371  if (error == boost::asio::error::operation_aborted ||
375  // transport is shutting down, ignore any errors
376  return;
377  }
378 
379  NFD_LOG_FACE_WARN("Receive operation failed: " << error.message());
380 }
381 
382 size_t
383 EthernetTransport::getInterfaceMtu()
384 {
385 #ifdef SIOCGIFMTU
386 #if defined(__APPLE__) || defined(__FreeBSD__)
387  // see bug #2328
388  using boost::asio::ip::udp;
389  udp::socket sock(getGlobalIoService(), udp::v4());
390  int fd = sock.native_handle();
391 #else
392  int fd = m_socket.native_handle();
393 #endif
394 
395  ifreq ifr{};
396  std::strncpy(ifr.ifr_name, m_interfaceName.c_str(), sizeof(ifr.ifr_name) - 1);
397 
398  if (::ioctl(fd, SIOCGIFMTU, &ifr) == 0) {
399  NFD_LOG_FACE_DEBUG("Interface MTU is " << ifr.ifr_mtu);
400  return static_cast<size_t>(ifr.ifr_mtu);
401  }
402 
403  NFD_LOG_FACE_WARN("Failed to get interface MTU: " << std::strerror(errno));
404 #endif
405 
406  NFD_LOG_FACE_DEBUG("Assuming default MTU of " << ethernet::MAX_DATA_LEN);
407  return ethernet::MAX_DATA_LEN;
408 }
409 
410 } // namespace face
411 } // namespace nfd
void setLocalUri(const FaceUri &uri)
Definition: transport.hpp:384
#define NFD_LOG_FACE_TRACE(msg)
Log a message at TRACE level.
Definition: face-log.hpp:74
contains information about a network interface
void setScope(ndn::nfd::FaceScope scope)
Definition: transport.hpp:408
void setMtu(ssize_t mtu)
Definition: transport.hpp:438
#define NFD_LOG_FACE_DEBUG(msg)
Log a message at DEBUG level.
Definition: face-log.hpp:77
EthernetTransport(const NetworkInterfaceInfo &interface, const ethernet::Address &mcastAddress)
Creates an Ethernet-based transport for multicast communication.
void receive(Packet &&packet)
receive a link-layer packet
Definition: transport.cpp:117
stores a packet along with the remote endpoint
Definition: transport.hpp:113
void doClose() final
performs Transport specific operations to close the transport
the transport is being closed due to a failure
#define NFD_LOG_FACE_WARN(msg)
Log a message at WARN level.
Definition: face-log.hpp:83
Copyright (c) 2014-2015, Regents of the University of California, Arizona Board of Regents...
the transport is closed, and can be safely deallocated
#define NFD_LOG_FACE_INFO(msg)
Log a message at INFO level.
Definition: face-log.hpp:80
void setLinkType(ndn::nfd::LinkType linkType)
Definition: transport.hpp:426
the transport is requested to be closed
void setPersistency(ndn::nfd::FacePersistency newPersistency)
changes face persistency setting
Definition: transport.cpp:151
#define NFD_LOG_INIT(name)
Definition: logger.hpp:122
TransportState getState() const
Definition: transport.hpp:445
#define PCAP_NETMASK_UNKNOWN
Copyright (c) 2014-2017, Regents of the University of California, Arizona Board of Regents...
void setState(TransportState newState)
set transport state
Definition: transport.cpp:174
void setRemoteUri(const FaceUri &uri)
Definition: transport.hpp:396
#define NFD_LOG_FACE_ERROR(msg)
Log a message at ERROR level.
Definition: face-log.hpp:86
boost::asio::io_service & getGlobalIoService()
Definition: global-io.cpp:41