NS-3 based Named Data Networking (NDN) simulator
ndnSIM 2.0: NDN, CCN, CCNx, content centric networks
API Documentation
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)",
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::beforeChangePersistency(ndn::nfd::FacePersistency newPersistency)
124 {
125  if (newPersistency != ndn::nfd::FACE_PERSISTENCY_PERMANENT) {
126  BOOST_THROW_EXCEPTION(
127  std::invalid_argument("EthernetTransport supports only FACE_PERSISTENCY_PERMANENT"));
128  }
129 }
130 
131 void EthernetTransport::doSend(Transport::Packet&& packet)
132 {
133  NFD_LOG_FACE_TRACE(__func__);
134 
135  sendPacket(packet.packet);
136 }
137 
138 void EthernetTransport::doClose()
139 {
140  NFD_LOG_FACE_TRACE(__func__);
141 
142  if (m_socket.is_open()) {
143  // Cancel all outstanding operations and close the socket.
144  // Use the non-throwing variants and ignore errors, if any.
145  boost::system::error_code error;
146  m_socket.cancel(error);
147  m_socket.close(error);
148  }
149  m_pcap.reset();
150 
151  // Ensure that the Transport stays alive at least
152  // until all pending handlers are dispatched
153  getGlobalIoService().post([this] {
154  this->setState(TransportState::CLOSED);
155  });
156 }
157 
158 void
159 EthernetTransport::pcapInit()
160 {
161  char errbuf[PCAP_ERRBUF_SIZE] = {};
162  m_pcap.reset(pcap_create(m_interfaceName.c_str(), errbuf));
163  if (!m_pcap)
164  BOOST_THROW_EXCEPTION(Error("pcap_create: " + std::string(errbuf)));
165 
166 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
167  // Enable "immediate mode", effectively disabling any read buffering in the kernel.
168  // This corresponds to the BIOCIMMEDIATE ioctl on BSD-like systems (including OS X)
169  // where libpcap uses a BPF device. On Linux this forces libpcap not to use TPACKET_V3,
170  // even if the kernel supports it, thus preventing bug #1511.
171  pcap_set_immediate_mode(m_pcap.get(), 1);
172 #endif
173 
174  if (pcap_activate(m_pcap.get()) < 0)
175  BOOST_THROW_EXCEPTION(Error("pcap_activate failed"));
176 
177  if (pcap_set_datalink(m_pcap.get(), DLT_EN10MB) < 0)
178  BOOST_THROW_EXCEPTION(Error("pcap_set_datalink: " + std::string(pcap_geterr(m_pcap.get()))));
179 
180  if (pcap_setdirection(m_pcap.get(), PCAP_D_IN) < 0)
181  // no need to throw on failure, BPF will filter unwanted packets anyway
182  NFD_LOG_FACE_WARN("pcap_setdirection failed: " << pcap_geterr(m_pcap.get()));
183 }
184 
185 void
186 EthernetTransport::setPacketFilter(const char* filterString)
187 {
188  bpf_program filter;
189  if (pcap_compile(m_pcap.get(), &filter, filterString, 1, PCAP_NETMASK_UNKNOWN) < 0)
190  BOOST_THROW_EXCEPTION(Error("pcap_compile: " + std::string(pcap_geterr(m_pcap.get()))));
191 
192  int ret = pcap_setfilter(m_pcap.get(), &filter);
193  pcap_freecode(&filter);
194  if (ret < 0)
195  BOOST_THROW_EXCEPTION(Error("pcap_setfilter: " + std::string(pcap_geterr(m_pcap.get()))));
196 }
197 
198 bool
199 EthernetTransport::joinMulticastGroup()
200 {
201 #if defined(__linux__)
202  packet_mreq mr{};
203  mr.mr_ifindex = m_interfaceIndex;
204  mr.mr_type = PACKET_MR_MULTICAST;
205  mr.mr_alen = m_destAddress.size();
206  std::memcpy(mr.mr_address, m_destAddress.data(), m_destAddress.size());
207 
208  if (::setsockopt(m_socket.native_handle(), SOL_PACKET,
209  PACKET_ADD_MEMBERSHIP, &mr, sizeof(mr)) == 0)
210  return true; // success
211 
212  NFD_LOG_FACE_WARN("setsockopt(PACKET_ADD_MEMBERSHIP) failed: " << std::strerror(errno));
213 #endif
214 
215 #if defined(SIOCADDMULTI)
216  ifreq ifr{};
217  std::strncpy(ifr.ifr_name, m_interfaceName.c_str(), sizeof(ifr.ifr_name) - 1);
218 
219 #if defined(__APPLE__) || defined(__FreeBSD__)
220  // see bug #2327
221  using boost::asio::ip::udp;
222  udp::socket sock(getGlobalIoService(), udp::v4());
223  int fd = sock.native_handle();
224 
225  /*
226  * Differences between Linux and the BSDs (including OS X):
227  * o BSD does not have ifr_hwaddr; use ifr_addr instead.
228  * o While OS X seems to accept both AF_LINK and AF_UNSPEC as the address
229  * family, FreeBSD explicitly requires AF_LINK, so we have to use AF_LINK
230  * and sockaddr_dl instead of the generic sockaddr structure.
231  * o BSD's sockaddr (and sockaddr_dl in particular) contains an additional
232  * field, sa_len (sdl_len), which must be set to the total length of the
233  * structure, including the length field itself.
234  * o We do not specify the interface name, thus sdl_nlen is left at 0 and
235  * LLADDR is effectively the same as sdl_data.
236  */
237  sockaddr_dl* sdl = reinterpret_cast<sockaddr_dl*>(&ifr.ifr_addr);
238  sdl->sdl_len = sizeof(ifr.ifr_addr);
239  sdl->sdl_family = AF_LINK;
240  sdl->sdl_alen = m_destAddress.size();
241  std::memcpy(LLADDR(sdl), m_destAddress.data(), m_destAddress.size());
242 
243  static_assert(sizeof(ifr.ifr_addr) >= offsetof(sockaddr_dl, sdl_data) + ethernet::ADDR_LEN,
244  "ifr_addr in struct ifreq is too small on this platform");
245 #else
246  int fd = m_socket.native_handle();
247 
248  ifr.ifr_hwaddr.sa_family = AF_UNSPEC;
249  std::memcpy(ifr.ifr_hwaddr.sa_data, m_destAddress.data(), m_destAddress.size());
250 
251  static_assert(sizeof(ifr.ifr_hwaddr.sa_data) >= ethernet::ADDR_LEN,
252  "ifr_hwaddr in struct ifreq is too small on this platform");
253 #endif
254 
255  if (::ioctl(fd, SIOCADDMULTI, &ifr) == 0)
256  return true; // success
257 
258  NFD_LOG_FACE_WARN("ioctl(SIOCADDMULTI) failed: " << std::strerror(errno));
259 #endif
260 
261  return false;
262 }
263 
264 void
265 EthernetTransport::sendPacket(const ndn::Block& block)
266 {
269  ndn::EncodingBuffer buffer(block);
270 
271  // pad with zeroes if the payload is too short
272  if (block.size() < ethernet::MIN_DATA_LEN) {
273  static const uint8_t padding[ethernet::MIN_DATA_LEN] = {};
274  buffer.appendByteArray(padding, ethernet::MIN_DATA_LEN - block.size());
275  }
276 
277  // construct and prepend the ethernet header
278  static uint16_t ethertype = htons(ethernet::ETHERTYPE_NDN);
279  buffer.prependByteArray(reinterpret_cast<const uint8_t*>(&ethertype), ethernet::TYPE_LEN);
280  buffer.prependByteArray(m_srcAddress.data(), m_srcAddress.size());
281  buffer.prependByteArray(m_destAddress.data(), m_destAddress.size());
282 
283  // send the packet
284  int sent = pcap_inject(m_pcap.get(), buffer.buf(), buffer.size());
285  if (sent < 0)
286  NFD_LOG_FACE_ERROR("pcap_inject failed: " << pcap_geterr(m_pcap.get()));
287  else if (static_cast<size_t>(sent) < buffer.size())
288  NFD_LOG_FACE_ERROR("Failed to send the full frame: bufsize=" << buffer.size() << " sent=" << sent);
289  else
290  // print block size because we don't want to count the padding in buffer
291  NFD_LOG_FACE_TRACE("Successfully sent: " << block.size() << " bytes");
292 }
293 
294 void
295 EthernetTransport::handleRead(const boost::system::error_code& error, size_t)
296 {
297  if (error)
298  return processErrorCode(error);
299 
300  pcap_pkthdr* header;
301  const uint8_t* packet;
302 
303  // read the pcap header and packet data
304  int ret = pcap_next_ex(m_pcap.get(), &header, &packet);
305  if (ret < 0)
306  NFD_LOG_FACE_ERROR("pcap_next_ex failed: " << pcap_geterr(m_pcap.get()));
307  else if (ret == 0)
308  NFD_LOG_FACE_WARN("Read timeout");
309  else
310  processIncomingPacket(header, packet);
311 
312 #ifdef _DEBUG
313  pcap_stat ps{};
314  ret = pcap_stats(m_pcap.get(), &ps);
315  if (ret < 0) {
316  NFD_LOG_FACE_DEBUG("pcap_stats failed: " << pcap_geterr(m_pcap.get()));
317  }
318  else if (ret == 0) {
319  if (ps.ps_drop - m_nDropped > 0)
320  NFD_LOG_FACE_DEBUG("Detected " << ps.ps_drop - m_nDropped << " dropped packet(s)");
321  m_nDropped = ps.ps_drop;
322  }
323 #endif
324 
325  m_socket.async_read_some(boost::asio::null_buffers(),
326  bind(&EthernetTransport::handleRead, this,
327  boost::asio::placeholders::error,
328  boost::asio::placeholders::bytes_transferred));
329 }
330 
331 void
332 EthernetTransport::processIncomingPacket(const pcap_pkthdr* header, const uint8_t* packet)
333 {
334  size_t length = header->caplen;
335  if (length < ethernet::HDR_LEN + ethernet::MIN_DATA_LEN) {
336  NFD_LOG_FACE_WARN("Received frame is too short (" << length << " bytes)");
337  return;
338  }
339 
340  const ether_header* eh = reinterpret_cast<const ether_header*>(packet);
341  const ethernet::Address sourceAddress(eh->ether_shost);
342 
343  // in some cases VLAN-tagged frames may survive the BPF filter,
344  // make sure we do not process those frames (see #3348)
345  if (ntohs(eh->ether_type) != ethernet::ETHERTYPE_NDN)
346  return;
347 
348  // check that our BPF filter is working correctly
349  BOOST_ASSERT_MSG(ethernet::Address(eh->ether_dhost) == m_destAddress,
350  "Received frame addressed to a different multicast group");
351  BOOST_ASSERT_MSG(sourceAddress != m_srcAddress,
352  "Received frame sent by this host");
353 
354  packet += ethernet::HDR_LEN;
355  length -= ethernet::HDR_LEN;
356 
357  bool isOk = false;
358  Block element;
359  std::tie(isOk, element) = Block::fromBuffer(packet, length);
360  if (!isOk) {
361  NFD_LOG_FACE_WARN("Received invalid packet from " << sourceAddress.toString());
362  return;
363  }
364 
365  NFD_LOG_FACE_TRACE("Received: " << element.size() << " bytes from " << sourceAddress.toString());
366 
367  Transport::Packet tp(std::move(element));
368  static_assert(sizeof(tp.remoteEndpoint) >= ethernet::ADDR_LEN,
369  "Transport::Packet::remoteEndpoint is too small");
370  std::memcpy(&tp.remoteEndpoint, sourceAddress.data(), sourceAddress.size());
371  this->receive(std::move(tp));
372 }
373 
374 void
375 EthernetTransport::processErrorCode(const boost::system::error_code& error)
376 {
377  NFD_LOG_FACE_TRACE(__func__);
378 
379  if (getState() == TransportState::CLOSING ||
380  getState() == TransportState::FAILED ||
381  getState() == TransportState::CLOSED ||
382  error == boost::asio::error::operation_aborted)
383  // transport is shutting down, ignore any errors
384  return;
385 
386  NFD_LOG_FACE_WARN("Receive operation failed: " << error.message());
387 }
388 
389 size_t
390 EthernetTransport::getInterfaceMtu()
391 {
392 #ifdef SIOCGIFMTU
393 #if defined(__APPLE__) || defined(__FreeBSD__)
394  // see bug #2328
395  using boost::asio::ip::udp;
396  udp::socket sock(getGlobalIoService(), udp::v4());
397  int fd = sock.native_handle();
398 #else
399  int fd = m_socket.native_handle();
400 #endif
401 
402  ifreq ifr{};
403  std::strncpy(ifr.ifr_name, m_interfaceName.c_str(), sizeof(ifr.ifr_name) - 1);
404 
405  if (::ioctl(fd, SIOCGIFMTU, &ifr) == 0) {
406  NFD_LOG_FACE_DEBUG("Interface MTU is " << ifr.ifr_mtu);
407  return static_cast<size_t>(ifr.ifr_mtu);
408  }
409 
410  NFD_LOG_FACE_WARN("Failed to get interface MTU: " << std::strerror(errno));
411 #endif
412 
413  NFD_LOG_FACE_DEBUG("Assuming default MTU of " << ethernet::MAX_DATA_LEN);
414  return ethernet::MAX_DATA_LEN;
415 }
416 
417 } // namespace face
418 } // namespace nfd
const size_t ADDR_LEN
Octets in one Ethernet address.
Definition: ethernet.hpp:42
static std::tuple< bool, Block > fromBuffer(ConstBufferPtr buffer, size_t offset)
Try to construct block from Buffer.
Definition: block.cpp:253
#define NFD_LOG_FACE_TRACE(msg)
Log a message at TRACE level.
Definition: face-log.hpp:74
represents an Ethernet hardware address
Definition: ethernet.hpp:53
represents the underlying protocol and address used by a Face
Definition: face-uri.hpp:44
#define NFD_LOG_FACE_ERROR(msg)
Log a message at ERROR level.
Definition: face-log.hpp:86
stores a packet along with the remote endpoint
Definition: transport.hpp:113
contains information about a network interface
detail::SimulatorIo & getGlobalIoService()
Definition: global-io.cpp:48
const size_t TYPE_LEN
Octets in Ethertype field.
Definition: ethernet.hpp:43
Class representing a wire element of NDN-TLV packet format.
Definition: block.hpp:43
the transport is being closed due to a failure
const size_t MIN_DATA_LEN
Min octets in Ethernet payload (assuming no 802.1Q tag)
Definition: ethernet.hpp:46
#define NFD_LOG_FACE_DEBUG(msg)
Log a message at DEBUG level.
Definition: face-log.hpp:77
size_t size() const
Definition: block.cpp:504
EncodingImpl< EncoderTag > EncodingBuffer
#define NFD_LOG_FACE_INFO(msg)
Log a message at INFO level.
Definition: face-log.hpp:80
Copyright (c) 2011-2015 Regents of the University of California.
Definition: ndn-common.hpp:40
the transport is closed, and can be safely deallocated
void post(const std::function< void()> &callback)
Definition: global-io.cpp:34
the transport is requested to be closed
const size_t MAX_DATA_LEN
Max octets in Ethernet payload.
Definition: ethernet.hpp:47
#define NFD_LOG_INIT(name)
Definition: logger.hpp:34
const size_t HDR_LEN
Total octets in Ethernet header (without 802.1Q tag)
Definition: ethernet.hpp:44
static FaceUri fromDev(const std::string &ifname)
create dev FaceUri from network device name
Definition: face-uri.cpp:160
#define PCAP_NETMASK_UNKNOWN
Copyright (c) 2014-2015, Regents of the University of California, Arizona Board of Regents...
const uint16_t ETHERTYPE_NDN
Definition: ethernet.hpp:40
#define NFD_LOG_FACE_WARN(msg)
Log a message at WARN level.
Definition: face-log.hpp:83