ethernet-transport.cpp
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * Copyright (c) 2014-2018, Regents of the University of California,
4  * Arizona Board of Regents,
5  * Colorado State University,
6  * University Pierre & Marie Curie, Sorbonne University,
7  * Washington University in St. Louis,
8  * Beijing Institute of Technology,
9  * The University of Memphis.
10  *
11  * This file is part of NFD (Named Data Networking Forwarding Daemon).
12  * See AUTHORS.md for complete list of NFD authors and contributors.
13  *
14  * NFD is free software: you can redistribute it and/or modify it under the terms
15  * of the GNU General Public License as published by the Free Software Foundation,
16  * either version 3 of the License, or (at your option) any later version.
17  *
18  * NFD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
19  * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
20  * PURPOSE. See the GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License along with
23  * NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
24  */
25 
26 #include "ethernet-transport.hpp"
27 #include "ethernet-protocol.hpp"
28 #include "core/global-io.hpp"
29 
30 #include <pcap/pcap.h>
31 
32 #include <cstring> // for memcpy()
33 
34 #include <boost/endian/conversion.hpp>
35 
36 namespace nfd {
37 namespace face {
38 
39 NFD_LOG_INIT(EthernetTransport);
40 
41 EthernetTransport::EthernetTransport(const ndn::net::NetworkInterface& localEndpoint,
42  const ethernet::Address& remoteEndpoint)
43  : m_socket(getGlobalIoService())
44  , m_pcap(localEndpoint.getName())
45  , m_srcAddress(localEndpoint.getEthernetAddress())
46  , m_destAddress(remoteEndpoint)
47  , m_interfaceName(localEndpoint.getName())
48  , m_hasRecentlyReceived(false)
49 #ifdef _DEBUG
50  , m_nDropped(0)
51 #endif
52 {
53  try {
54  m_pcap.activate(DLT_EN10MB);
55  m_socket.assign(m_pcap.getFd());
56  }
57  catch (const PcapHelper::Error& e) {
58  BOOST_THROW_EXCEPTION(Error(e.what()));
59  }
60 
61  asyncRead();
62 }
63 
64 void
66 {
67  NFD_LOG_FACE_TRACE(__func__);
68 
69  if (m_socket.is_open()) {
70  // Cancel all outstanding operations and close the socket.
71  // Use the non-throwing variants and ignore errors, if any.
72  boost::system::error_code error;
73  m_socket.cancel(error);
74  m_socket.close(error);
75  }
76  m_pcap.close();
77 
78  // Ensure that the Transport stays alive at least
79  // until all pending handlers are dispatched
80  getGlobalIoService().post([this] {
82  });
83 }
84 
85 void
86 EthernetTransport::doSend(Transport::Packet&& packet)
87 {
88  NFD_LOG_FACE_TRACE(__func__);
89 
90  sendPacket(packet.packet);
91 }
92 
93 void
94 EthernetTransport::sendPacket(const ndn::Block& block)
95 {
96  ndn::EncodingBuffer buffer(block);
97 
98  // pad with zeroes if the payload is too short
99  if (block.size() < ethernet::MIN_DATA_LEN) {
100  static const uint8_t padding[ethernet::MIN_DATA_LEN] = {};
101  buffer.appendByteArray(padding, ethernet::MIN_DATA_LEN - block.size());
102  }
103 
104  // construct and prepend the ethernet header
105  uint16_t ethertype = boost::endian::native_to_big(ethernet::ETHERTYPE_NDN);
106  buffer.prependByteArray(reinterpret_cast<const uint8_t*>(&ethertype), ethernet::TYPE_LEN);
107  buffer.prependByteArray(m_srcAddress.data(), m_srcAddress.size());
108  buffer.prependByteArray(m_destAddress.data(), m_destAddress.size());
109 
110  // send the frame
111  int sent = pcap_inject(m_pcap, buffer.buf(), buffer.size());
112  if (sent < 0)
113  handleError("Send operation failed: " + m_pcap.getLastError());
114  else if (static_cast<size_t>(sent) < buffer.size())
115  handleError("Failed to send the full frame: size=" + to_string(buffer.size()) +
116  " sent=" + to_string(sent));
117  else
118  // print block size because we don't want to count the padding in buffer
119  NFD_LOG_FACE_TRACE("Successfully sent: " << block.size() << " bytes");
120 }
121 
122 void
123 EthernetTransport::asyncRead()
124 {
125  m_socket.async_read_some(boost::asio::null_buffers(),
126  [this] (const auto& e, auto) { this->handleRead(e); });
127 }
128 
129 void
130 EthernetTransport::handleRead(const boost::system::error_code& error)
131 {
132  if (error) {
133  // boost::asio::error::operation_aborted must be checked first: in that case, the Transport
134  // may already have been destructed, therefore it's unsafe to call getState() or do logging.
135  if (error != boost::asio::error::operation_aborted &&
139  handleError("Receive operation failed: " + error.message());
140  }
141  return;
142  }
143 
144  const uint8_t* pkt;
145  size_t len;
146  std::string err;
147  std::tie(pkt, len, err) = m_pcap.readNextPacket();
148 
149  if (pkt == nullptr) {
150  NFD_LOG_FACE_WARN("Read error: " << err);
151  }
152  else {
153  const ether_header* eh;
154  std::tie(eh, err) = ethernet::checkFrameHeader(pkt, len, m_srcAddress,
155  m_destAddress.isMulticast() ? m_destAddress : m_srcAddress);
156  if (eh == nullptr) {
157  NFD_LOG_FACE_WARN(err);
158  }
159  else {
160  ethernet::Address sender(eh->ether_shost);
161  pkt += ethernet::HDR_LEN;
162  len -= ethernet::HDR_LEN;
163  receivePayload(pkt, len, sender);
164  }
165  }
166 
167 #ifdef _DEBUG
168  size_t nDropped = m_pcap.getNDropped();
169  if (nDropped - m_nDropped > 0)
170  NFD_LOG_FACE_DEBUG("Detected " << nDropped - m_nDropped << " dropped frame(s)");
171  m_nDropped = nDropped;
172 #endif
173 
174  asyncRead();
175 }
176 
177 void
178 EthernetTransport::receivePayload(const uint8_t* payload, size_t length,
179  const ethernet::Address& sender)
180 {
181  NFD_LOG_FACE_TRACE("Received: " << length << " bytes from " << sender);
182 
183  bool isOk = false;
184  Block element;
185  std::tie(isOk, element) = Block::fromBuffer(payload, length);
186  if (!isOk) {
187  NFD_LOG_FACE_WARN("Failed to parse incoming packet from " << sender);
188  // This packet won't extend the face lifetime
189  return;
190  }
191  m_hasRecentlyReceived = true;
192 
193  Transport::Packet tp(std::move(element));
194  static_assert(sizeof(tp.remoteEndpoint) >= ethernet::ADDR_LEN,
195  "Transport::Packet::remoteEndpoint is too small");
196  if (m_destAddress.isMulticast()) {
197  std::memcpy(&tp.remoteEndpoint, sender.data(), sender.size());
198  }
199  this->receive(std::move(tp));
200 }
201 
202 void
203 EthernetTransport::handleError(const std::string& errorMessage)
204 {
205  if (getPersistency() == ndn::nfd::FACE_PERSISTENCY_PERMANENT) {
206  NFD_LOG_FACE_DEBUG("Permanent face ignores error: " << errorMessage);
207  return;
208  }
209 
210  NFD_LOG_FACE_ERROR(errorMessage);
212  doClose();
213 }
214 
215 } // namespace face
216 } // namespace nfd
#define NFD_LOG_FACE_TRACE(msg)
Log a message at TRACE level.
Definition: face-log.hpp:79
boost::asio::posix::stream_descriptor m_socket
#define NFD_LOG_FACE_DEBUG(msg)
Log a message at DEBUG level.
Definition: face-log.hpp:82
void receive(Packet &&packet)
receive a link-layer packet
Definition: transport.cpp:120
stores a packet along with the remote endpoint
Definition: transport.hpp:122
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:88
size_t getNDropped() const
Get the number of packets dropped by the kernel, as reported by libpcap.
std::string getLastError() const
Get last error message.
Definition: pcap-helper.cpp:95
Copyright (c) 2014-2015, Regents of the University of California, Arizona Board of Regents...
Definition: algorithm.hpp:32
void receivePayload(const uint8_t *payload, size_t length, const ethernet::Address &sender)
Processes the payload of an incoming frame.
the transport is closed, and can be safely deallocated
std::tuple< const uint8_t *, size_t, std::string > readNextPacket() const
Read the next packet captured on the interface.
the transport is being closed gracefully, either by the peer or by a call to close() ...
std::pair< const ether_header *, std::string > checkFrameHeader(const uint8_t *packet, size_t length, const Address &localAddr, const Address &destAddr)
EthernetTransport(const ndn::net::NetworkInterface &localEndpoint, const ethernet::Address &remoteEndpoint)
void activate(int dlt)
Start capturing packets.
Definition: pcap-helper.cpp:60
int getFd() const
Obtain a file descriptor that can be used in calls such as select(2) and poll(2). ...
Definition: pcap-helper.cpp:83
ndn::nfd::FacePersistency getPersistency() const
Definition: transport.hpp:451
#define NFD_LOG_INIT(name)
Definition: logger.hpp:31
TransportState getState() const
Definition: transport.hpp:494
void close()
Stop capturing and close the handle.
Definition: pcap-helper.cpp:74
EndpointId remoteEndpoint
identifies the remote endpoint
Definition: transport.hpp:141
void setState(TransportState newState)
set transport state
Definition: transport.cpp:177
#define NFD_LOG_FACE_ERROR(msg)
Log a message at ERROR level.
Definition: face-log.hpp:91
boost::asio::io_service & getGlobalIoService()
Definition: global-io.cpp:42