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-2018, 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 "core/global-io.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  BOOST_THROW_EXCEPTION(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(Transport::Packet&& packet)
106 {
107  NFD_LOG_FACE_TRACE(__func__);
108 
109  sendPacket(packet.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  Transport::Packet tp(std::move(element));
213  static_assert(sizeof(tp.remoteEndpoint) >= ethernet::ADDR_LEN,
214  "Transport::Packet::remoteEndpoint is too small");
215  if (m_destAddress.isMulticast()) {
216  std::memcpy(&tp.remoteEndpoint, sender.data(), sender.size());
217  }
218  this->receive(std::move(tp));
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
const size_t MIN_DATA_LEN
Min octets in Ethernet payload (assuming no 802.1Q tag)
Definition: ethernet.hpp:45
static std::tuple< bool, Block > fromBuffer(ConstBufferPtr buffer, size_t offset)
Try to parse Block from a wire buffer.
Definition: block.cpp:193
interface can be used to send and receive packets
#define NFD_LOG_FACE_TRACE(msg)
Log a message at TRACE level.
Definition: face-log.hpp:79
void activate(int dlt)
Start capturing packets.
Definition: pcap-helper.cpp:60
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.
Definition: face-log.hpp:91
util::Signal< NetworkInterface, InterfaceState, InterfaceState > onStateChanged
Fires when interface state changes.
stores a packet along with the remote endpoint
Definition: transport.hpp:122
EthernetTransport(const ndn::net::NetworkInterface &localEndpoint, const ethernet::Address &remoteEndpoint)
InterfaceState
Indicates the state of a network interface.
detail::SimulatorIo & getGlobalIoService()
Definition: global-io.cpp:48
Represents a TLV element of NDN packet format.
Definition: block.hpp:42
void receivePayload(const uint8_t *payload, size_t length, const ethernet::Address &sender)
Processes the payload of an incoming frame.
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.
Definition: face-log.hpp:82
size_t size() const
Get size of encoded wire, including Type-Length-Value.
Definition: block.cpp:298
TransportState getState() const
Definition: transport.hpp:494
Copyright (c) 2011-2015 Regents of the University of California.
Definition: ndn-common.hpp:40
EndpointId remoteEndpoint
identifies the remote endpoint
Definition: transport.hpp:141
the transport is closed, and can be safely deallocated
void post(const std::function< void()> &callback)
Definition: global-io.cpp:34
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
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()
std::string getLastError() const
Get last error message.
Definition: pcap-helper.cpp:95
std::pair< const ether_header *, std::string > checkFrameHeader(const uint8_t *packet, size_t length, const Address &localAddr, const Address &destAddr)
void close()
Stop capturing and close the handle.
Definition: pcap-helper.cpp:74
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:451
int getFd() const
Obtain a file descriptor that can be used in calls such as select(2) and poll(2).
Definition: pcap-helper.cpp:83
Base class for Ethernet-based Transports.
size_t getNDropped() const
Get the number of packets dropped by the kernel, as reported by libpcap.
std::string to_string(const V &v)
Definition: backports.hpp:67
std::tuple< const uint8_t *, size_t, std::string > readNextPacket() const
Read the next packet captured on the interface.
void setState(TransportState newState)
set transport state
Definition: transport.cpp:177
the transport is up and can transmit packets
void receive(Packet &&packet)
receive a link-layer packet
Definition: transport.cpp:120
#define NFD_LOG_INIT(name)
Definition: logger.hpp:31
EncodingImpl< EncoderTag > EncodingBuffer
#define NFD_LOG_FACE_WARN(msg)
Log a message at WARN level.
Definition: face-log.hpp:88
the transport is temporarily down, and is being recovered