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-2020, 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  // Set initial transport state based upon the state of the underlying NetworkInterface
62  handleNetifStateChange(localEndpoint.getState());
63 
64  m_netifStateChangedConn = localEndpoint.onStateChanged.connect(
65  [this] (ndn::net::InterfaceState, ndn::net::InterfaceState newState) {
66  handleNetifStateChange(newState);
67  });
68 
69  m_netifMtuChangedConn = localEndpoint.onMtuChanged.connect(
70  [this] (uint32_t, uint32_t mtu) {
71  setMtu(mtu);
72  });
73 
74  asyncRead();
75 }
76 
77 void
79 {
80  NFD_LOG_FACE_TRACE(__func__);
81 
82  if (m_socket.is_open()) {
83  // Cancel all outstanding operations and close the socket.
84  // Use the non-throwing variants and ignore errors, if any.
85  boost::system::error_code error;
86  m_socket.cancel(error);
87  m_socket.close(error);
88  }
89  m_pcap.close();
90 
91  // Ensure that the Transport stays alive at least
92  // until all pending handlers are dispatched
93  getGlobalIoService().post([this] {
95  });
96 }
97 
98 void
99 EthernetTransport::handleNetifStateChange(ndn::net::InterfaceState netifState)
100 {
101  NFD_LOG_FACE_TRACE("netif is " << netifState);
102  if (netifState == ndn::net::InterfaceState::RUNNING) {
103  if (getState() == TransportState::DOWN) {
105  }
106  }
107  else if (getState() == TransportState::UP) {
109  }
110 }
111 
112 void
113 EthernetTransport::doSend(const Block& packet)
114 {
115  NFD_LOG_FACE_TRACE(__func__);
116 
117  sendPacket(packet);
118 }
119 
120 void
121 EthernetTransport::sendPacket(const ndn::Block& block)
122 {
123  ndn::EncodingBuffer buffer(block);
124 
125  // pad with zeroes if the payload is too short
126  if (block.size() < ethernet::MIN_DATA_LEN) {
127  static const uint8_t padding[ethernet::MIN_DATA_LEN] = {};
128  buffer.appendByteArray(padding, ethernet::MIN_DATA_LEN - block.size());
129  }
130 
131  // construct and prepend the ethernet header
132  uint16_t ethertype = boost::endian::native_to_big(ethernet::ETHERTYPE_NDN);
133  buffer.prependByteArray(reinterpret_cast<const uint8_t*>(&ethertype), ethernet::TYPE_LEN);
134  buffer.prependByteArray(m_srcAddress.data(), m_srcAddress.size());
135  buffer.prependByteArray(m_destAddress.data(), m_destAddress.size());
136 
137  // send the frame
138  int sent = pcap_inject(m_pcap, buffer.buf(), buffer.size());
139  if (sent < 0)
140  handleError("Send operation failed: " + m_pcap.getLastError());
141  else if (static_cast<size_t>(sent) < buffer.size())
142  handleError("Failed to send the full frame: size=" + to_string(buffer.size()) +
143  " sent=" + to_string(sent));
144  else
145  // print block size because we don't want to count the padding in buffer
146  NFD_LOG_FACE_TRACE("Successfully sent: " << block.size() << " bytes");
147 }
148 
149 void
150 EthernetTransport::asyncRead()
151 {
152  m_socket.async_read_some(boost::asio::null_buffers(),
153  [this] (const auto& e, auto) { this->handleRead(e); });
154 }
155 
156 void
157 EthernetTransport::handleRead(const boost::system::error_code& error)
158 {
159  if (error) {
160  // boost::asio::error::operation_aborted must be checked first: in that case, the Transport
161  // may already have been destructed, therefore it's unsafe to call getState() or do logging.
162  if (error != boost::asio::error::operation_aborted &&
166  handleError("Receive operation failed: " + error.message());
167  }
168  return;
169  }
170 
171  const uint8_t* pkt;
172  size_t len;
173  std::string err;
174  std::tie(pkt, len, err) = m_pcap.readNextPacket();
175 
176  if (pkt == nullptr) {
177  NFD_LOG_FACE_WARN("Read error: " << err);
178  }
179  else {
180  const ether_header* eh;
181  std::tie(eh, err) = ethernet::checkFrameHeader(pkt, len, m_srcAddress,
182  m_destAddress.isMulticast() ? m_destAddress : m_srcAddress);
183  if (eh == nullptr) {
184  NFD_LOG_FACE_WARN(err);
185  }
186  else {
187  ethernet::Address sender(eh->ether_shost);
188  pkt += ethernet::HDR_LEN;
189  len -= ethernet::HDR_LEN;
190  receivePayload(pkt, len, sender);
191  }
192  }
193 
194 #ifdef _DEBUG
195  size_t nDropped = m_pcap.getNDropped();
196  if (nDropped - m_nDropped > 0)
197  NFD_LOG_FACE_DEBUG("Detected " << nDropped - m_nDropped << " dropped frame(s)");
198  m_nDropped = nDropped;
199 #endif
200 
201  asyncRead();
202 }
203 
204 void
205 EthernetTransport::receivePayload(const uint8_t* payload, size_t length,
206  const ethernet::Address& sender)
207 {
208  NFD_LOG_FACE_TRACE("Received: " << length << " bytes from " << sender);
209 
210  bool isOk = false;
211  Block element;
212  std::tie(isOk, element) = Block::fromBuffer(payload, length);
213  if (!isOk) {
214  NFD_LOG_FACE_WARN("Failed to parse incoming packet from " << sender);
215  // This packet won't extend the face lifetime
216  return;
217  }
218  m_hasRecentlyReceived = true;
219 
220  static_assert(sizeof(EndpointId) >= ethernet::ADDR_LEN, "EndpointId is too small");
221  EndpointId endpoint = 0;
222  if (m_destAddress.isMulticast()) {
223  std::memcpy(&endpoint, sender.data(), sender.size());
224  }
225 
226  this->receive(element, endpoint);
227 }
228 
229 void
230 EthernetTransport::handleError(const std::string& errorMessage)
231 {
232  if (getPersistency() == ndn::nfd::FACE_PERSISTENCY_PERMANENT) {
233  NFD_LOG_FACE_DEBUG("Permanent face ignores error: " << errorMessage);
234  return;
235  }
236 
237  NFD_LOG_FACE_ERROR(errorMessage);
239  doClose();
240 }
241 
242 } // namespace face
243 } // namespace nfd
size_t getNDropped() const
Get the number of packets dropped by the kernel, as reported by libpcap.
#define NFD_LOG_FACE_TRACE(msg)
Log a message at TRACE level.
boost::asio::posix::stream_descriptor m_socket
void setMtu(ssize_t mtu)
Definition: transport.cpp:126
#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:71
void doClose() final
performs Transport specific operations to close the transport
the transport is being closed due to a failure
std::tuple< const uint8_t *, size_t, std::string > readNextPacket() const
Read the next packet captured on the interface.
#define NFD_LOG_FACE_WARN(msg)
Log a message at WARN level.
TransportState getState() const
Definition: transport.hpp:451
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::string getLastError() const
Get last error message.
Definition: pcap-helper.cpp:99
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)
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
void activate(int dlt)
Start capturing packets.
Definition: pcap-helper.cpp:64
#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:113
void close()
Stop capturing and close the handle.
Definition: pcap-helper.cpp:78
ndn::nfd::FacePersistency getPersistency() const
Definition: transport.hpp:415
void setState(TransportState newState)
set transport state
Definition: transport.cpp:187
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