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-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 
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  m_netifStateConn = localEndpoint.onStateChanged.connect(
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,
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 {
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
nfd::face::EthernetTransport::receivePayload
void receivePayload(const uint8_t *payload, size_t length, const ethernet::Address &sender)
Processes the payload of an incoming frame.
Definition: ethernet-transport.cpp:197
global.hpp
NFD_LOG_FACE_ERROR
#define NFD_LOG_FACE_ERROR(msg)
Log a message at ERROR level.
Definition: face-common.hpp:145
nfd::face::EthernetTransport::m_socket
boost::asio::posix::stream_descriptor m_socket
Definition: ethernet-transport.hpp:102
nfd::face::TransportState::CLOSED
@ CLOSED
the transport is closed, and can be safely deallocated
nfd::detail::SimulatorIo::post
void post(const std::function< void()> &callback)
Definition: global.cpp:35
nfd::face::EthernetTransport::m_destAddress
ethernet::Address m_destAddress
Definition: ethernet-transport.hpp:105
nfd::face::PcapHelper::getFd
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::net::NetworkInterface
Represents one network interface attached to the host.
Definition: network-interface.hpp:70
ndn::nfd::FACE_PERSISTENCY_PERMANENT
@ FACE_PERSISTENCY_PERMANENT
face is permanent
Definition: nfd-constants.hpp:49
ndn::ethernet::Address
represents an Ethernet hardware address
Definition: ethernet.hpp:53
ethernet-protocol.hpp
nfd::face::Transport::setState
void setState(TransportState newState)
set transport state
Definition: transport.cpp:173
nfd::face::EthernetTransport::m_pcap
PcapHelper m_pcap
Definition: ethernet-transport.hpp:103
ndn::ethernet::ETHERTYPE_NDN
const uint16_t ETHERTYPE_NDN
Definition: ethernet.hpp:39
nfd::face::EthernetTransport::m_srcAddress
ethernet::Address m_srcAddress
Definition: ethernet-transport.hpp:104
nfd::face::TransportState::DOWN
@ DOWN
the transport is temporarily down, and is being recovered
nfd::face::EthernetTransport::EthernetTransport
EthernetTransport(const ndn::net::NetworkInterface &localEndpoint, const ethernet::Address &remoteEndpoint)
Definition: ethernet-transport.cpp:41
NFD_LOG_FACE_DEBUG
#define NFD_LOG_FACE_DEBUG(msg)
Log a message at DEBUG level.
Definition: face-common.hpp:136
nfd::face::Transport::getPersistency
ndn::nfd::FacePersistency getPersistency() const
Definition: transport.hpp:424
NDN_THROW_NESTED
#define NDN_THROW_NESTED(e)
Definition: exception.hpp:71
nfd::face::PcapHelper::close
void close()
Stop capturing and close the handle.
Definition: pcap-helper.cpp:78
nfd::getGlobalIoService
detail::SimulatorIo & getGlobalIoService()
Returns the global io_service instance for the calling thread.
Definition: global.cpp:49
nfd::face::PcapHelper::readNextPacket
std::tuple< const uint8_t *, size_t, std::string > readNextPacket() const
Read the next packet captured on the interface.
Definition: pcap-helper.cpp:128
nfd::face::TransportState::CLOSING
@ CLOSING
the transport is being closed gracefully, either by the peer or by a call to close()
nfd
Copyright (c) 2011-2015 Regents of the University of California.
Definition: ndn-common.hpp:40
ndn::Block::fromBuffer
static NDN_CXX_NODISCARD std::tuple< bool, Block > fromBuffer(ConstBufferPtr buffer, size_t offset)
Try to parse Block from a wire buffer.
Definition: block.cpp:194
ndn::net::NetworkInterface::onStateChanged
util::Signal< NetworkInterface, InterfaceState, InterfaceState > onStateChanged
Fires when interface state changes.
Definition: network-interface.hpp:74
ethernet-transport.hpp
ndn::ethernet::TYPE_LEN
const size_t TYPE_LEN
Octets in Ethertype field.
Definition: ethernet.hpp:42
NFD_LOG_FACE_TRACE
#define NFD_LOG_FACE_TRACE(msg)
Log a message at TRACE level.
Definition: face-common.hpp:133
nfd::face::EthernetTransport::Error
Definition: ethernet-transport.hpp:45
ndn::ethernet::HDR_LEN
const size_t HDR_LEN
Total octets in Ethernet header (without 802.1Q tag)
Definition: ethernet.hpp:43
nfd::face::PcapHelper::getLastError
std::string getLastError() const
Get last error message.
Definition: pcap-helper.cpp:99
ndn::net::InterfaceState
InterfaceState
Indicates the state of a network interface.
Definition: network-interface.hpp:50
ndn::ethernet::MIN_DATA_LEN
const size_t MIN_DATA_LEN
Min octets in Ethernet payload (assuming no 802.1Q tag)
Definition: ethernet.hpp:45
nfd::face::PcapHelper::activate
void activate(int dlt)
Start capturing packets.
Definition: pcap-helper.cpp:64
nfd::face::EthernetTransport
Base class for Ethernet-based Transports.
Definition: ethernet-transport.hpp:42
nfd::face::TransportState::UP
@ UP
the transport is up and can transmit packets
ndn::ethernet::ADDR_LEN
const size_t ADDR_LEN
Octets in one Ethernet address.
Definition: ethernet.hpp:41
ndn::Block
Represents a TLV element of NDN packet format.
Definition: block.hpp:43
ndn::Block::size
size_t size() const
Return the size of the encoded wire, i.e.
Definition: block.cpp:290
ndn::to_string
std::string to_string(const T &val)
Definition: backports.hpp:102
nfd::face::PcapHelper::Error
Definition: pcap-helper.hpp:49
nfd::face::TransportState::FAILED
@ FAILED
the transport is being closed due to a failure
nfd::face::PcapHelper::getNDropped
size_t getNDropped() const
Get the number of packets dropped by the kernel, as reported by libpcap.
Definition: pcap-helper.cpp:105
nfd::face::Transport::getState
TransportState getState() const
Definition: transport.hpp:467
nfd::face::EndpointId
uint64_t EndpointId
Identifies a remote endpoint on the link.
Definition: face-common.hpp:65
nfd::face::Transport::receive
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
ndn::ethernet::Address::isMulticast
bool isMulticast() const
True if this is a multicast address.
Definition: ethernet.cpp:66
NFD_LOG_FACE_WARN
#define NFD_LOG_FACE_WARN(msg)
Log a message at WARN level.
Definition: face-common.hpp:142
ndn::net::InterfaceState::RUNNING
@ RUNNING
interface can be used to send and receive packets
nfd::ethernet::checkFrameHeader
std::pair< const ether_header *, std::string > checkFrameHeader(const uint8_t *packet, size_t length, const Address &localAddr, const Address &destAddr)
Definition: ethernet-protocol.cpp:34
NFD_LOG_INIT
#define NFD_LOG_INIT(name)
Definition: logger.hpp:31
ndn::encoding::EncodingBuffer
EncodingImpl< EncoderTag > EncodingBuffer
Definition: encoding-buffer-fwd.hpp:38
nfd::face::EthernetTransport::doClose
void doClose() final
performs Transport specific operations to close the transport
Definition: ethernet-transport.cpp:70