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-2022, 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 <boost/endian/conversion.hpp>
33 
34 namespace nfd::face {
35 
36 NFD_LOG_INIT(EthernetTransport);
37 
38 EthernetTransport::EthernetTransport(const ndn::net::NetworkInterface& localEndpoint,
39  const ethernet::Address& remoteEndpoint)
40  : m_socket(getGlobalIoService())
41  , m_pcap(localEndpoint.getName())
42  , m_srcAddress(localEndpoint.getEthernetAddress())
43  , m_destAddress(remoteEndpoint)
44  , m_interfaceName(localEndpoint.getName())
45  , m_hasRecentlyReceived(false)
46 #ifdef _DEBUG
47  , m_nDropped(0)
48 #endif
49 {
50  try {
51  m_pcap.activate(DLT_EN10MB);
52  m_socket.assign(m_pcap.getFd());
53  }
54  catch (const PcapHelper::Error& e) {
55  NDN_THROW_NESTED(Error(e.what()));
56  }
57 
58  // Set initial transport state based upon the state of the underlying NetworkInterface
59  handleNetifStateChange(localEndpoint.getState());
60 
61  m_netifStateChangedConn = localEndpoint.onStateChanged.connect(
62  [this] (ndn::net::InterfaceState, ndn::net::InterfaceState newState) {
63  handleNetifStateChange(newState);
64  });
65 
66  m_netifMtuChangedConn = localEndpoint.onMtuChanged.connect(
67  [this] (uint32_t, uint32_t mtu) {
68  setMtu(mtu);
69  });
70 
71  asyncRead();
72 }
73 
74 void
76 {
77  NFD_LOG_FACE_TRACE(__func__);
78 
79  if (m_socket.is_open()) {
80  // Cancel all outstanding operations and close the socket.
81  // Use the non-throwing variants and ignore errors, if any.
82  boost::system::error_code error;
83  m_socket.cancel(error);
84  m_socket.close(error);
85  }
86  m_pcap.close();
87 
88  // Ensure that the Transport stays alive at least
89  // until all pending handlers are dispatched
90  getGlobalIoService().post([this] {
92  });
93 }
94 
95 void
96 EthernetTransport::handleNetifStateChange(ndn::net::InterfaceState netifState)
97 {
98  NFD_LOG_FACE_TRACE("netif is " << netifState);
99  if (netifState == ndn::net::InterfaceState::RUNNING) {
100  if (getState() == TransportState::DOWN) {
102  }
103  }
104  else if (getState() == TransportState::UP) {
106  }
107 }
108 
109 void
110 EthernetTransport::doSend(const Block& packet)
111 {
112  NFD_LOG_FACE_TRACE(__func__);
113 
114  sendPacket(packet);
115 }
116 
117 void
118 EthernetTransport::sendPacket(const ndn::Block& block)
119 {
120  ndn::EncodingBuffer buffer(block);
121 
122  // pad with zeroes if the payload is too short
123  if (block.size() < ethernet::MIN_DATA_LEN) {
124  static const uint8_t padding[ethernet::MIN_DATA_LEN] = {};
125  buffer.appendBytes(ndn::make_span(padding).subspan(block.size()));
126  }
127 
128  // construct and prepend the ethernet header
129  uint16_t ethertype = boost::endian::native_to_big(ethernet::ETHERTYPE_NDN);
130  buffer.prependBytes({reinterpret_cast<const uint8_t*>(&ethertype), ethernet::TYPE_LEN});
131  buffer.prependBytes(m_srcAddress);
132  buffer.prependBytes(m_destAddress);
133 
134  // send the frame
135  int sent = pcap_inject(m_pcap, buffer.data(), buffer.size());
136  if (sent < 0)
137  handleError("Send operation failed: " + m_pcap.getLastError());
138  else if (static_cast<size_t>(sent) < buffer.size())
139  handleError("Failed to send the full frame: size=" + to_string(buffer.size()) +
140  " sent=" + to_string(sent));
141  else
142  // print block size because we don't want to count the padding in buffer
143  NFD_LOG_FACE_TRACE("Successfully sent: " << block.size() << " bytes");
144 }
145 
146 void
147 EthernetTransport::asyncRead()
148 {
149  m_socket.async_read_some(boost::asio::null_buffers(),
150  [this] (const auto& e, auto) { this->handleRead(e); });
151 }
152 
153 void
154 EthernetTransport::handleRead(const boost::system::error_code& error)
155 {
156  if (error) {
157  // boost::asio::error::operation_aborted must be checked first: in that case, the Transport
158  // may already have been destructed, therefore it's unsafe to call getState() or do logging.
159  if (error != boost::asio::error::operation_aborted &&
163  handleError("Receive operation failed: " + error.message());
164  }
165  return;
166  }
167 
168  auto [pkt, readErr] = m_pcap.readNextPacket();
169  if (pkt.empty()) {
170  NFD_LOG_FACE_DEBUG("Read error: " << readErr);
171  }
172  else {
173  auto [eh, frameErr] = ethernet::checkFrameHeader(pkt, m_srcAddress,
174  m_destAddress.isMulticast() ? m_destAddress : m_srcAddress);
175  if (eh == nullptr) {
176  NFD_LOG_FACE_WARN(frameErr);
177  }
178  else {
179  ethernet::Address sender(eh->ether_shost);
180  pkt = pkt.subspan(ethernet::HDR_LEN);
181  receivePayload(pkt, sender);
182  }
183  }
184 
185 #ifdef _DEBUG
186  size_t nDropped = m_pcap.getNDropped();
187  if (nDropped - m_nDropped > 0)
188  NFD_LOG_FACE_DEBUG("Detected " << nDropped - m_nDropped << " dropped frame(s)");
189  m_nDropped = nDropped;
190 #endif
191 
192  asyncRead();
193 }
194 
195 void
196 EthernetTransport::receivePayload(span<const uint8_t> payload, const ethernet::Address& sender)
197 {
198  NFD_LOG_FACE_TRACE("Received: " << payload.size() << " bytes from " << sender);
199 
200  auto [isOk, element] = Block::fromBuffer(payload);
201  if (!isOk) {
202  NFD_LOG_FACE_WARN("Failed to parse incoming packet from " << sender);
203  // This packet won't extend the face lifetime
204  return;
205  }
206  m_hasRecentlyReceived = true;
207 
208  this->receive(element, m_destAddress.isMulticast() ? sender : EndpointId{});
209 }
210 
211 void
212 EthernetTransport::handleError(const std::string& errorMessage)
213 {
214  if (getPersistency() == ndn::nfd::FACE_PERSISTENCY_PERMANENT) {
215  NFD_LOG_FACE_DEBUG("Permanent face ignores error: " << errorMessage);
216  return;
217  }
218 
219  NFD_LOG_FACE_ERROR(errorMessage);
221  doClose();
222 }
223 
224 } // namespace nfd::face
void receivePayload(span< const uint8_t > payload, const ethernet::Address &sender)
Processes the payload of an incoming frame.
void doClose() final
Performs Transport specific operations to close the transport.
boost::asio::posix::stream_descriptor m_socket
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:93
std::string getLastError() const noexcept
Get last error message.
void activate(int dlt)
Start capturing packets.
Definition: pcap-helper.cpp:64
size_t getNDropped() const
Get the number of packets dropped by the kernel, as reported by libpcap.
std::tuple< span< const uint8_t >, std::string > readNextPacket() const noexcept
Read the next packet captured on the interface.
void close() noexcept
Stop capturing and close the handle.
Definition: pcap-helper.cpp:84
void receive(const Block &packet, const EndpointId &endpoint={})
Pass a received link-layer packet to the upper layer for further processing.
Definition: transport.cpp:101
ndn::nfd::FacePersistency getPersistency() const noexcept
Returns the current persistency setting of the transport.
Definition: transport.hpp:227
void setMtu(ssize_t mtu) noexcept
Definition: transport.cpp:114
TransportState getState() const noexcept
Returns the current transport state.
Definition: transport.hpp:291
void setState(TransportState newState)
Set transport state.
Definition: transport.cpp:175
#define NFD_LOG_FACE_ERROR(msg)
Log a message at ERROR level.
#define NFD_LOG_FACE_DEBUG(msg)
Log a message at DEBUG level.
#define NFD_LOG_FACE_WARN(msg)
Log a message at WARN level.
#define NFD_LOG_FACE_TRACE(msg)
Log a message at TRACE level.
#define NFD_LOG_INIT(name)
Definition: logger.hpp:31
std::tuple< const ether_header *, std::string > checkFrameHeader(span< const uint8_t > packet, const Address &localAddr, const Address &destAddr)
@ CLOSED
the transport is closed, and can be safely deallocated
@ CLOSING
the transport is being closed gracefully, either by the peer or by a call to close()
@ FAILED
the transport is being closed due to a failure
@ DOWN
the transport is temporarily down, and is being recovered
@ UP
the transport is up and can transmit packets
std::variant< std::monostate, ethernet::Address, udp::Endpoint > EndpointId
Identifies a remote endpoint on the link.
Definition: face-common.hpp:77
boost::asio::io_service & getGlobalIoService()
Returns the global io_service instance for the calling thread.
Definition: global.cpp:36