NS-3 based Named Data Networking (NDN) simulator
ndnSIM 2.5: NDN, CCN, CCNx, content centric networks
API Documentation
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 <cstring> // for memcpy()
33 
34 #include <boost/endian/conversion.hpp>
35 
36 namespace nfd {
37 namespace face {
38 
40 
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(
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.appendBytes(ndn::make_span(padding).subspan(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.prependBytes({reinterpret_cast<const uint8_t*>(&ethertype), ethernet::TYPE_LEN});
134  buffer.prependBytes(m_srcAddress);
135  buffer.prependBytes(m_destAddress);
136 
137  // send the frame
138  int sent = pcap_inject(m_pcap, buffer.data(), 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.
166  handleError("Receive operation failed: " + error.message());
167  }
168  return;
169  }
170 
171  span<const uint8_t> pkt;
172  std::string err;
173  std::tie(pkt, err) = m_pcap.readNextPacket();
174 
175  if (pkt.empty()) {
176  NFD_LOG_FACE_WARN("Read error: " << err);
177  }
178  else {
179  const ether_header* eh;
180  std::tie(eh, err) = ethernet::checkFrameHeader(pkt, m_srcAddress,
182  if (eh == nullptr) {
183  NFD_LOG_FACE_WARN(err);
184  }
185  else {
186  ethernet::Address sender(eh->ether_shost);
187  pkt = pkt.subspan(ethernet::HDR_LEN);
188  receivePayload(pkt, sender);
189  }
190  }
191 
192 #ifdef _DEBUG
193  size_t nDropped = m_pcap.getNDropped();
194  if (nDropped - m_nDropped > 0)
195  NFD_LOG_FACE_DEBUG("Detected " << nDropped - m_nDropped << " dropped frame(s)");
196  m_nDropped = nDropped;
197 #endif
198 
199  asyncRead();
200 }
201 
202 void
203 EthernetTransport::receivePayload(span<const uint8_t> payload, const ethernet::Address& sender)
204 {
205  NFD_LOG_FACE_TRACE("Received: " << payload.size() << " bytes from " << sender);
206 
207  bool isOk = false;
208  Block element;
209  std::tie(isOk, element) = Block::fromBuffer(payload);
210  if (!isOk) {
211  NFD_LOG_FACE_WARN("Failed to parse incoming packet from " << sender);
212  // This packet won't extend the face lifetime
213  return;
214  }
215  m_hasRecentlyReceived = true;
216 
217  static_assert(sizeof(EndpointId) >= ethernet::ADDR_LEN, "EndpointId is too small");
218  EndpointId endpoint = 0;
219  if (m_destAddress.isMulticast()) {
220  std::memcpy(&endpoint, sender.data(), sender.size());
221  }
222 
223  this->receive(element, endpoint);
224 }
225 
226 void
227 EthernetTransport::handleError(const std::string& errorMessage)
228 {
230  NFD_LOG_FACE_DEBUG("Permanent face ignores error: " << errorMessage);
231  return;
232  }
233 
234  NFD_LOG_FACE_ERROR(errorMessage);
236  doClose();
237 }
238 
239 } // namespace face
240 } // namespace nfd
#define NDN_THROW_NESTED(e)
Definition: exception.hpp:71
static NDN_CXX_NODISCARD std::tuple< bool, Block > fromBuffer(ConstBufferPtr buffer, size_t offset=0)
Try to parse Block from a wire buffer.
Definition: block.cpp:162
InterfaceState getState() const
Returns the current state of the interface.
const size_t MIN_DATA_LEN
Min octets in Ethernet payload (assuming no 802.1Q tag)
Definition: ethernet.hpp:45
interface can be used to send and receive packets
#define NFD_LOG_INIT(name)
Definition: logger.hpp:31
std::string to_string(const T &val)
Definition: backports.hpp:86
#define NFD_LOG_FACE_TRACE(msg)
Log a message at TRACE level.
void activate(int dlt)
Start capturing packets.
Definition: pcap-helper.cpp:66
const size_t ADDR_LEN
Octets in one Ethernet address.
Definition: ethernet.hpp:41
#define NFD_LOG_FACE_ERROR(msg)
Log a message at ERROR level.
util::Signal< NetworkInterface, InterfaceState, InterfaceState > onStateChanged
Fires when interface state changes.
EthernetTransport(const ndn::net::NetworkInterface &localEndpoint, const ethernet::Address &remoteEndpoint)
util::Signal< NetworkInterface, uint32_t, uint32_t > onMtuChanged
Fires when interface mtu changes.
InterfaceState
Indicates the state of a network interface.
detail::SimulatorIo & getGlobalIoService()
Returns the global io_service instance for the calling thread.
Definition: global.cpp:49
Represents a TLV element of the NDN packet format.
Definition: block.hpp:44
uint64_t EndpointId
Identifies a remote endpoint on the link.
Definition: face-common.hpp:71
void setMtu(ssize_t mtu)
Definition: transport.cpp:126
the transport is being closed due to a failure
void doClose() final
performs Transport specific operations to close the transport
Represents one network interface attached to the host.
#define NFD_LOG_FACE_DEBUG(msg)
Log a message at DEBUG level.
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
size_t size() const
Return the size of the encoded wire, i.e., of the whole TLV.
Definition: block.cpp:294
TransportState getState() const
Definition: transport.hpp:451
Copyright (c) 2011-2015 Regents of the University of California.
Definition: ndn-common.hpp:39
std::tuple< const ether_header *, std::string > checkFrameHeader(span< const uint8_t > packet, const Address &localAddr, const Address &destAddr)
the transport is closed, and can be safely deallocated
void post(const std::function< void()> &callback)
Definition: global.cpp:35
const size_t HDR_LEN
Total octets in Ethernet header (without 802.1Q tag)
Definition: ethernet.hpp:43
boost::asio::posix::stream_descriptor m_socket
void close() noexcept
Stop capturing and close the handle.
Definition: pcap-helper.cpp:82
std::string getLastError() const noexcept
Get last error message.
const size_t TYPE_LEN
Octets in Ethertype field.
Definition: ethernet.hpp:42
const uint16_t ETHERTYPE_NDN
Definition: ethernet.hpp:39
the transport is being closed gracefully, either by the peer or by a call to close() ...
bool isMulticast() const
True if this is a multicast address.
Definition: ethernet.cpp:66
represents an Ethernet hardware address
Definition: ethernet.hpp:52
ndn::nfd::FacePersistency getPersistency() const
Definition: transport.hpp:415
int getFd() const
Obtain a file descriptor that can be used in calls such as select(2) and poll(2). ...
Definition: pcap-helper.cpp:91
Base class for Ethernet-based Transports.
size_t getNDropped() const
Get the number of packets dropped by the kernel, as reported by libpcap.
void setState(TransportState newState)
set transport state
Definition: transport.cpp:187
the transport is up and can transmit packets
void receivePayload(span< const uint8_t > payload, const ethernet::Address &sender)
Processes the payload of an incoming frame.
std::tuple< span< const uint8_t >, std::string > readNextPacket() const noexcept
Read the next packet captured on the interface.
EncodingImpl< EncoderTag > EncodingBuffer
#define NFD_LOG_FACE_WARN(msg)
Log a message at WARN level.
the transport is temporarily down, and is being recovered