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-2017, 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 <arpa/inet.h> // for htons()
33 #include <cstring> // for memcpy()
34 
35 namespace nfd {
36 namespace face {
37 
38 NFD_LOG_INIT("EthernetTransport");
39 
40 EthernetTransport::EthernetTransport(const ndn::net::NetworkInterface& localEndpoint,
41  const ethernet::Address& remoteEndpoint)
42  : m_socket(getGlobalIoService())
43  , m_pcap(localEndpoint.getName())
44  , m_srcAddress(localEndpoint.getEthernetAddress())
45  , m_destAddress(remoteEndpoint)
46  , m_interfaceName(localEndpoint.getName())
47  , m_hasRecentlyReceived(false)
48 #ifdef _DEBUG
49  , m_nDropped(0)
50 #endif
51 {
52  try {
53  m_pcap.activate(DLT_EN10MB);
54  m_socket.assign(m_pcap.getFd());
55  }
56  catch (const PcapHelper::Error& e) {
57  BOOST_THROW_EXCEPTION(Error(e.what()));
58  }
59 
60  asyncRead();
61 }
62 
63 void
65 {
66  NFD_LOG_FACE_TRACE(__func__);
67 
68  if (m_socket.is_open()) {
69  // Cancel all outstanding operations and close the socket.
70  // Use the non-throwing variants and ignore errors, if any.
71  boost::system::error_code error;
72  m_socket.cancel(error);
73  m_socket.close(error);
74  }
75  m_pcap.close();
76 
77  // Ensure that the Transport stays alive at least
78  // until all pending handlers are dispatched
79  getGlobalIoService().post([this] {
81  });
82 }
83 
84 void
85 EthernetTransport::doSend(Transport::Packet&& packet)
86 {
87  NFD_LOG_FACE_TRACE(__func__);
88 
89  sendPacket(packet.packet);
90 }
91 
92 void
93 EthernetTransport::sendPacket(const ndn::Block& block)
94 {
95  ndn::EncodingBuffer buffer(block);
96 
97  // pad with zeroes if the payload is too short
98  if (block.size() < ethernet::MIN_DATA_LEN) {
99  static const uint8_t padding[ethernet::MIN_DATA_LEN] = {};
100  buffer.appendByteArray(padding, ethernet::MIN_DATA_LEN - block.size());
101  }
102 
103  // construct and prepend the ethernet header
104  static uint16_t ethertype = htons(ethernet::ETHERTYPE_NDN);
105  buffer.prependByteArray(reinterpret_cast<const uint8_t*>(&ethertype), ethernet::TYPE_LEN);
106  buffer.prependByteArray(m_srcAddress.data(), m_srcAddress.size());
107  buffer.prependByteArray(m_destAddress.data(), m_destAddress.size());
108 
109  // send the frame
110  int sent = pcap_inject(m_pcap, buffer.buf(), buffer.size());
111  if (sent < 0)
112  handleError("Send operation failed: " + m_pcap.getLastError());
113  else if (static_cast<size_t>(sent) < buffer.size())
114  handleError("Failed to send the full frame: size=" + to_string(buffer.size()) +
115  " sent=" + to_string(sent));
116  else
117  // print block size because we don't want to count the padding in buffer
118  NFD_LOG_FACE_TRACE("Successfully sent: " << block.size() << " bytes");
119 }
120 
121 void
122 EthernetTransport::asyncRead()
123 {
124  m_socket.async_read_some(boost::asio::null_buffers(),
125  bind(&EthernetTransport::handleRead, this,
126  boost::asio::placeholders::error));
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: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: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:97
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:62
int getFd() const
Obtain a file descriptor that can be used in calls such as select(2) and poll(2). ...
Definition: pcap-helper.cpp:85
ndn::nfd::FacePersistency getPersistency() const
Definition: transport.hpp:414
#define NFD_LOG_INIT(name)
Definition: logger.hpp:122
TransportState getState() const
Definition: transport.hpp:445
void close()
Stop capturing and close the handle.
Definition: pcap-helper.cpp:76
EndpointId remoteEndpoint
identifies the remote endpoint
Definition: transport.hpp:132
void setState(TransportState newState)
set transport state
Definition: transport.cpp:174
#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:41