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-2019, 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 "common/global.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  NDN_THROW_NESTED(Error(e.what()));
59  }
60 
61  m_netifStateConn = localEndpoint.onStateChanged.connect(
62  [=] (ndn::net::InterfaceState, ndn::net::InterfaceState newState) {
63  handleNetifStateChange(newState);
64  });
65 
66  asyncRead();
67 }
68 
69 void
71 {
72  NFD_LOG_FACE_TRACE(__func__);
73 
74  if (m_socket.is_open()) {
75  // Cancel all outstanding operations and close the socket.
76  // Use the non-throwing variants and ignore errors, if any.
77  boost::system::error_code error;
78  m_socket.cancel(error);
79  m_socket.close(error);
80  }
81  m_pcap.close();
82 
83  // Ensure that the Transport stays alive at least
84  // until all pending handlers are dispatched
85  getGlobalIoService().post([this] {
87  });
88 }
89 
90 void
91 EthernetTransport::handleNetifStateChange(ndn::net::InterfaceState netifState)
92 {
93  NFD_LOG_FACE_TRACE("netif is " << netifState);
94  if (netifState == ndn::net::InterfaceState::RUNNING) {
95  if (getState() == TransportState::DOWN) {
97  }
98  }
99  else if (getState() == TransportState::UP) {
101  }
102 }
103 
104 void
105 EthernetTransport::doSend(const Block& packet, const EndpointId&)
106 {
107  NFD_LOG_FACE_TRACE(__func__);
108 
109  sendPacket(packet);
110 }
111 
112 void
113 EthernetTransport::sendPacket(const ndn::Block& block)
114 {
115  ndn::EncodingBuffer buffer(block);
116 
117  // pad with zeroes if the payload is too short
118  if (block.size() < ethernet::MIN_DATA_LEN) {
119  static const uint8_t padding[ethernet::MIN_DATA_LEN] = {};
120  buffer.appendByteArray(padding, ethernet::MIN_DATA_LEN - block.size());
121  }
122 
123  // construct and prepend the ethernet header
124  uint16_t ethertype = boost::endian::native_to_big(ethernet::ETHERTYPE_NDN);
125  buffer.prependByteArray(reinterpret_cast<const uint8_t*>(&ethertype), ethernet::TYPE_LEN);
126  buffer.prependByteArray(m_srcAddress.data(), m_srcAddress.size());
127  buffer.prependByteArray(m_destAddress.data(), m_destAddress.size());
128 
129  // send the frame
130  int sent = pcap_inject(m_pcap, buffer.buf(), buffer.size());
131  if (sent < 0)
132  handleError("Send operation failed: " + m_pcap.getLastError());
133  else if (static_cast<size_t>(sent) < buffer.size())
134  handleError("Failed to send the full frame: size=" + to_string(buffer.size()) +
135  " sent=" + to_string(sent));
136  else
137  // print block size because we don't want to count the padding in buffer
138  NFD_LOG_FACE_TRACE("Successfully sent: " << block.size() << " bytes");
139 }
140 
141 void
142 EthernetTransport::asyncRead()
143 {
144  m_socket.async_read_some(boost::asio::null_buffers(),
145  [this] (const auto& e, auto) { this->handleRead(e); });
146 }
147 
148 void
149 EthernetTransport::handleRead(const boost::system::error_code& error)
150 {
151  if (error) {
152  // boost::asio::error::operation_aborted must be checked first: in that case, the Transport
153  // may already have been destructed, therefore it's unsafe to call getState() or do logging.
154  if (error != boost::asio::error::operation_aborted &&
158  handleError("Receive operation failed: " + error.message());
159  }
160  return;
161  }
162 
163  const uint8_t* pkt;
164  size_t len;
165  std::string err;
166  std::tie(pkt, len, err) = m_pcap.readNextPacket();
167 
168  if (pkt == nullptr) {
169  NFD_LOG_FACE_WARN("Read error: " << err);
170  }
171  else {
172  const ether_header* eh;
173  std::tie(eh, err) = ethernet::checkFrameHeader(pkt, len, m_srcAddress,
174  m_destAddress.isMulticast() ? m_destAddress : m_srcAddress);
175  if (eh == nullptr) {
176  NFD_LOG_FACE_WARN(err);
177  }
178  else {
179  ethernet::Address sender(eh->ether_shost);
180  pkt += ethernet::HDR_LEN;
181  len -= ethernet::HDR_LEN;
182  receivePayload(pkt, len, sender);
183  }
184  }
185 
186 #ifdef _DEBUG
187  size_t nDropped = m_pcap.getNDropped();
188  if (nDropped - m_nDropped > 0)
189  NFD_LOG_FACE_DEBUG("Detected " << nDropped - m_nDropped << " dropped frame(s)");
190  m_nDropped = nDropped;
191 #endif
192 
193  asyncRead();
194 }
195 
196 void
197 EthernetTransport::receivePayload(const uint8_t* payload, size_t length,
198  const ethernet::Address& sender)
199 {
200  NFD_LOG_FACE_TRACE("Received: " << length << " bytes from " << sender);
201 
202  bool isOk = false;
203  Block element;
204  std::tie(isOk, element) = Block::fromBuffer(payload, length);
205  if (!isOk) {
206  NFD_LOG_FACE_WARN("Failed to parse incoming packet from " << sender);
207  // This packet won't extend the face lifetime
208  return;
209  }
210  m_hasRecentlyReceived = true;
211 
212  static_assert(sizeof(EndpointId) >= ethernet::ADDR_LEN, "EndpointId is too small");
213  EndpointId endpoint = 0;
214  if (m_destAddress.isMulticast()) {
215  std::memcpy(&endpoint, sender.data(), sender.size());
216  }
217 
218  this->receive(element, endpoint);
219 }
220 
221 void
222 EthernetTransport::handleError(const std::string& errorMessage)
223 {
224  if (getPersistency() == ndn::nfd::FACE_PERSISTENCY_PERMANENT) {
225  NFD_LOG_FACE_DEBUG("Permanent face ignores error: " << errorMessage);
226  return;
227  }
228 
229  NFD_LOG_FACE_ERROR(errorMessage);
231  doClose();
232 }
233 
234 } // namespace face
235 } // namespace nfd
#define NFD_LOG_FACE_TRACE(msg)
Log a message at TRACE level.
boost::asio::posix::stream_descriptor m_socket
#define NFD_LOG_FACE_DEBUG(msg)
Log a message at DEBUG level.
uint64_t EndpointId
Identifies a remote endpoint on the link.
Definition: face-common.hpp:65
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.
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:99
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:64
int getFd() const
Obtain a file descriptor that can be used in calls such as select(2) and poll(2). ...
Definition: pcap-helper.cpp:87
ndn::nfd::FacePersistency getPersistency() const
Definition: transport.hpp:424
#define NFD_LOG_INIT(name)
Definition: logger.hpp:31
void receive(const Block &packet, const EndpointId &endpoint=0)
Pass a received link-layer packet to the upper layer for further processing.
Definition: transport.cpp:115
TransportState getState() const
Definition: transport.hpp:467
void close()
Stop capturing and close the handle.
Definition: pcap-helper.cpp:78
void setState(TransportState newState)
set transport state
Definition: transport.cpp:173
the transport is up and can transmit packets
#define NFD_LOG_FACE_ERROR(msg)
Log a message at ERROR level.
the transport is temporarily down, and is being recovered
boost::asio::io_service & getGlobalIoService()
Returns the global io_service instance for the calling thread.
Definition: global.cpp:36