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-2024, 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 <array>
33 
34 #include <boost/asio/defer.hpp>
35 #include <boost/endian/conversion.hpp>
36 
37 namespace nfd::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 {
49  try {
50  m_pcap.activate(DLT_EN10MB);
51  m_socket.assign(m_pcap.getFd());
52  }
53  catch (const PcapHelper::Error& e) {
54  NDN_THROW_NESTED(Error(e.what()));
55  }
56 
57  // Set initial transport state based upon the state of the underlying NetworkInterface
58  handleNetifStateChange(localEndpoint.getState());
59 
60  m_netifStateChangedConn = localEndpoint.onStateChanged.connect(
61  [this] (ndn::net::InterfaceState, ndn::net::InterfaceState newState) {
62  handleNetifStateChange(newState);
63  });
64 
65  m_netifMtuChangedConn = localEndpoint.onMtuChanged.connect(
66  [this] (uint32_t, uint32_t mtu) {
67  setMtu(mtu);
68  });
69 
70  asyncRead();
71 }
72 
73 void
75 {
76  NFD_LOG_FACE_TRACE(__func__);
77 
78  if (m_socket.is_open()) {
79  // Cancel all outstanding operations and close the socket.
80  // Use the non-throwing variants and ignore errors, if any.
81  boost::system::error_code error;
82  m_socket.cancel(error);
83  m_socket.close(error);
84  }
85  m_pcap.close();
86 
87  // Ensure that the Transport stays alive at least
88  // until all pending handlers are dispatched
89  boost::asio::defer(getGlobalIoService(), [this] {
91  });
92 }
93 
94 void
95 EthernetTransport::handleNetifStateChange(ndn::net::InterfaceState netifState)
96 {
97  NFD_LOG_FACE_TRACE("netif is " << netifState);
98  if (netifState == ndn::net::InterfaceState::RUNNING) {
99  if (getState() == TransportState::DOWN) {
101  }
102  }
103  else if (getState() == TransportState::UP) {
105  }
106 }
107 
108 void
109 EthernetTransport::doSend(const Block& packet)
110 {
111  NFD_LOG_FACE_TRACE(__func__);
112 
113  sendPacket(packet);
114 }
115 
116 void
117 EthernetTransport::sendPacket(const ndn::Block& block)
118 {
119  ndn::EncodingBuffer buffer(block);
120 
121  // pad with zeroes if the payload is too short
122  if (block.size() < ethernet::MIN_DATA_LEN) {
123  static const std::array<uint8_t, ethernet::MIN_DATA_LEN> padding{};
124  buffer.appendBytes(ndn::span(padding).subspan(block.size()));
125  }
126 
127  // construct and prepend the ethernet header
128 #if BOOST_VERSION >= 107200
129  constexpr
130 #endif
131  uint16_t ethertype = boost::endian::native_to_big(ethernet::ETHERTYPE_NDN);
132  buffer.prependBytes({reinterpret_cast<const uint8_t*>(&ethertype), ethernet::TYPE_LEN});
133  buffer.prependBytes(m_srcAddress);
134  buffer.prependBytes(m_destAddress);
135 
136  // send the frame
137  int sent = pcap_inject(m_pcap, buffer.data(), buffer.size());
138  if (sent < 0)
139  handleError("Send operation failed: " + m_pcap.getLastError());
140  else if (static_cast<size_t>(sent) < buffer.size())
141  handleError("Failed to send the full frame: size=" + std::to_string(buffer.size()) +
142  " sent=" + std::to_string(sent));
143  else
144  // print block size because we don't want to count the padding in buffer
145  NFD_LOG_FACE_TRACE("Successfully sent: " << block.size() << " bytes");
146 }
147 
148 void
149 EthernetTransport::asyncRead()
150 {
151  m_socket.async_wait(boost::asio::posix::stream_descriptor::wait_read,
152  [this] (const auto& e) { this->handleRead(e); });
153 }
154 
155 void
156 EthernetTransport::handleRead(const boost::system::error_code& error)
157 {
158  if (error) {
159  // boost::asio::error::operation_aborted must be checked first: in that case, the Transport
160  // may already have been destructed, therefore it's unsafe to call getState() or do logging.
161  if (error != boost::asio::error::operation_aborted &&
165  handleError("Receive operation failed: " + error.message());
166  }
167  return;
168  }
169 
170  auto [pkt, readErr] = m_pcap.readNextPacket();
171  if (pkt.empty()) {
172  NFD_LOG_FACE_DEBUG("Read error: " << readErr);
173  }
174  else {
175  auto [eh, frameErr] = ethernet::checkFrameHeader(pkt, m_srcAddress,
176  m_destAddress.isMulticast() ? m_destAddress : m_srcAddress);
177  if (eh == nullptr) {
178  NFD_LOG_FACE_WARN(frameErr);
179  }
180  else {
181  ethernet::Address sender(eh->ether_shost);
182  pkt = pkt.subspan(ethernet::HDR_LEN);
183  receivePayload(pkt, sender);
184  }
185  }
186 
187 #ifndef NDEBUG
188  size_t nDropped = m_pcap.getNDropped();
189  if (nDropped - m_nDropped > 0)
190  NFD_LOG_FACE_DEBUG("Detected " << nDropped - m_nDropped << " dropped frame(s)");
191  m_nDropped = nDropped;
192 #endif
193 
194  asyncRead();
195 }
196 
197 void
198 EthernetTransport::receivePayload(span<const uint8_t> payload, const ethernet::Address& sender)
199 {
200  NFD_LOG_FACE_TRACE("Received: " << payload.size() << " bytes from " << sender);
201 
202  auto [isOk, element] = Block::fromBuffer(payload);
203  if (!isOk) {
204  NFD_LOG_FACE_WARN("Failed to parse incoming packet from " << sender);
205  // This packet won't extend the face lifetime
206  return;
207  }
208  m_hasRecentlyReceived = true;
209 
210  this->receive(element, m_destAddress.isMulticast() ? sender : EndpointId{});
211 }
212 
213 void
214 EthernetTransport::handleError(const std::string& errorMessage)
215 {
216  if (getPersistency() == ndn::nfd::FACE_PERSISTENCY_PERMANENT) {
217  NFD_LOG_FACE_DEBUG("Permanent face ignores error: " << errorMessage);
218  return;
219  }
220 
221  NFD_LOG_FACE_ERROR(errorMessage);
223  doClose();
224 }
225 
226 } // 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:236
void setMtu(ssize_t mtu) noexcept
Definition: transport.cpp:114
TransportState getState() const noexcept
Returns the current transport state.
Definition: transport.hpp:300
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:78
boost::asio::io_context & getGlobalIoService()
Returns the global io_context instance for the calling thread.
Definition: global.cpp:36