NS-3 based Named Data Networking (NDN) simulator
ndnSIM 2.5: NDN, CCN, CCNx, content centric networks
API Documentation
ethernet-channel.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-channel.hpp"
27 #include "ethernet-protocol.hpp"
28 #include "face.hpp"
29 #include "generic-link-service.hpp"
31 #include "common/global.hpp"
32 
33 #include <boost/range/adaptor/map.hpp>
34 #include <pcap/pcap.h>
35 
36 namespace nfd {
37 namespace face {
38 
40 
41 EthernetChannel::EthernetChannel(shared_ptr<const ndn::net::NetworkInterface> localEndpoint,
42  time::nanoseconds idleTimeout)
43  : m_localEndpoint(std::move(localEndpoint))
44  , m_isListening(false)
45  , m_socket(getGlobalIoService())
46  , m_pcap(m_localEndpoint->getName())
47  , m_idleFaceTimeout(idleTimeout)
48 #ifdef _DEBUG
49  , m_nDropped(0)
50 #endif
51 {
52  setUri(FaceUri::fromDev(m_localEndpoint->getName()));
53  NFD_LOG_CHAN_INFO("Creating channel");
54 }
55 
56 void
58  const FaceParams& params,
59  const FaceCreatedCallback& onFaceCreated,
60  const FaceCreationFailedCallback& onConnectFailed)
61 {
62  shared_ptr<Face> face;
63  try {
64  face = createFace(remoteEndpoint, params).second;
65  }
66  catch (const boost::system::system_error& e) {
67  NFD_LOG_CHAN_DEBUG("Face creation for " << remoteEndpoint << " failed: " << e.what());
68  if (onConnectFailed)
69  onConnectFailed(504, "Face creation failed: "s + e.what());
70  return;
71  }
72 
73  // Need to invoke the callback regardless of whether or not we had already
74  // created the face so that control responses and such can be sent
75  onFaceCreated(face);
76 }
77 
78 void
80  const FaceCreationFailedCallback& onFaceCreationFailed)
81 {
82  if (isListening()) {
83  NFD_LOG_CHAN_WARN("Already listening");
84  return;
85  }
86  m_isListening = true;
87 
88  try {
89  m_pcap.activate(DLT_EN10MB);
90  m_socket.assign(m_pcap.getFd());
91  }
92  catch (const PcapHelper::Error& e) {
93  NDN_THROW_NESTED(Error(e.what()));
94  }
95  updateFilter();
96 
97  asyncRead(onFaceCreated, onFaceCreationFailed);
98  NFD_LOG_CHAN_DEBUG("Started listening");
99 }
100 
101 void
102 EthernetChannel::asyncRead(const FaceCreatedCallback& onFaceCreated,
103  const FaceCreationFailedCallback& onReceiveFailed)
104 {
105  m_socket.async_read_some(boost::asio::null_buffers(),
106  [=] (const auto& e, auto) { this->handleRead(e, onFaceCreated, onReceiveFailed); });
107 }
108 
109 void
110 EthernetChannel::handleRead(const boost::system::error_code& error,
111  const FaceCreatedCallback& onFaceCreated,
112  const FaceCreationFailedCallback& onReceiveFailed)
113 {
114  if (error) {
116  NFD_LOG_CHAN_DEBUG("Receive failed: " << error.message());
117  if (onReceiveFailed)
118  onReceiveFailed(500, "Receive failed: " + error.message());
119  }
120  return;
121  }
122 
123  span<const uint8_t> pkt;
124  std::string err;
125  std::tie(pkt, err) = m_pcap.readNextPacket();
126 
127  if (pkt.empty()) {
128  NFD_LOG_CHAN_WARN("Read error: " << err);
129  }
130  else {
131  const ether_header* eh;
132  std::tie(eh, err) = ethernet::checkFrameHeader(pkt, m_localEndpoint->getEthernetAddress(),
133  m_localEndpoint->getEthernetAddress());
134  if (eh == nullptr) {
135  NFD_LOG_CHAN_DEBUG(err);
136  }
137  else {
138  ethernet::Address sender(eh->ether_shost);
139  pkt = pkt.subspan(ethernet::HDR_LEN);
140  processIncomingPacket(pkt, sender, onFaceCreated, onReceiveFailed);
141  }
142  }
143 
144 #ifdef _DEBUG
145  size_t nDropped = m_pcap.getNDropped();
146  if (nDropped - m_nDropped > 0)
147  NFD_LOG_CHAN_DEBUG("Detected " << nDropped - m_nDropped << " dropped frame(s)");
148  m_nDropped = nDropped;
149 #endif
150 
151  asyncRead(onFaceCreated, onReceiveFailed);
152 }
153 
154 void
155 EthernetChannel::processIncomingPacket(span<const uint8_t> packet,
156  const ethernet::Address& sender,
157  const FaceCreatedCallback& onFaceCreated,
158  const FaceCreationFailedCallback& onReceiveFailed)
159 {
160  NFD_LOG_CHAN_TRACE("New peer " << sender);
161 
162  bool isCreated = false;
163  shared_ptr<Face> face;
164  try {
165  FaceParams params;
167  std::tie(isCreated, face) = createFace(sender, params);
168  }
169  catch (const EthernetTransport::Error& e) {
170  NFD_LOG_CHAN_DEBUG("Face creation for " << sender << " failed: " << e.what());
171  if (onReceiveFailed)
172  onReceiveFailed(504, "Face creation failed: "s + e.what());
173  return;
174  }
175 
176  if (isCreated)
177  onFaceCreated(face);
178  else
179  NFD_LOG_CHAN_DEBUG("Received frame for existing face");
180 
181  // dispatch the packet to the face for processing
182  auto* transport = static_cast<UnicastEthernetTransport*>(face->getTransport());
183  transport->receivePayload(packet, sender);
184 }
185 
186 std::pair<bool, shared_ptr<Face>>
187 EthernetChannel::createFace(const ethernet::Address& remoteEndpoint,
188  const FaceParams& params)
189 {
190  auto it = m_channelFaces.find(remoteEndpoint);
191  if (it != m_channelFaces.end()) {
192  // we already have a face for this endpoint, so reuse it
193  NFD_LOG_CHAN_TRACE("Reusing existing face for " << remoteEndpoint);
194  return {false, it->second};
195  }
196 
197  // else, create a new face
198  GenericLinkService::Options options;
199  options.allowFragmentation = true;
200  options.allowReassembly = true;
201  options.reliabilityOptions.isEnabled = params.wantLpReliability;
202  if (params.mtu) {
203  options.overrideMtu = *params.mtu;
204  }
205 
206  auto linkService = make_unique<GenericLinkService>(options);
207  auto transport = make_unique<UnicastEthernetTransport>(*m_localEndpoint, remoteEndpoint,
208  params.persistency, m_idleFaceTimeout);
209  auto face = make_shared<Face>(std::move(linkService), std::move(transport));
210  face->setChannel(shared_from_this()); // use weak_from_this() in C++17
211 
212  m_channelFaces[remoteEndpoint] = face;
213  connectFaceClosedSignal(*face, [this, remoteEndpoint] {
214  m_channelFaces.erase(remoteEndpoint);
215  updateFilter();
216  });
217  updateFilter();
218 
219  return {true, face};
220 }
221 
222 void
223 EthernetChannel::updateFilter()
224 {
225  if (!isListening())
226  return;
227 
228  std::string filter = "(ether proto " + to_string(ethernet::ETHERTYPE_NDN) +
229  ") && (ether dst " + m_localEndpoint->getEthernetAddress().toString() + ")";
230  for (const auto& addr : m_channelFaces | boost::adaptors::map_keys) {
231  filter += " && (not ether src " + addr.toString() + ")";
232  }
233  // "not vlan" must appear last in the filter expression, or the
234  // rest of the filter won't work as intended, see pcap-filter(7)
235  filter += " && (not vlan)";
236 
237  NFD_LOG_CHAN_TRACE("Updating filter: " << filter);
238  m_pcap.setPacketFilter(filter.data());
239 }
240 
241 } // namespace face
242 } // namespace nfd
#define NDN_THROW_NESTED(e)
Definition: exception.hpp:71
void connect(const ethernet::Address &remoteEndpoint, const FaceParams &params, const FaceCreatedCallback &onFaceCreated, const FaceCreationFailedCallback &onConnectFailed)
Create a unicast Ethernet face toward remoteEndpoint.
void setUri(const FaceUri &uri)
Definition: channel.cpp:35
#define NFD_LOG_INIT(name)
Definition: logger.hpp:31
std::string to_string(const T &val)
Definition: backports.hpp:86
void activate(int dlt)
Start capturing packets.
Definition: pcap-helper.cpp:66
ndn::nfd::FacePersistency persistency
Definition: face-common.hpp:80
STL namespace.
detail::SimulatorIo & getGlobalIoService()
Returns the global io_service instance for the calling thread.
Definition: global.cpp:49
std::function< void(uint32_t status, const std::string &reason)> FaceCreationFailedCallback
Prototype for the callback that is invoked when a face fails to be created.
Definition: channel.hpp:90
void setPacketFilter(const char *filter) const
Install a BPF filter on the receiving socket.
Class implementing Ethernet-based channel to create faces.
void connectFaceClosedSignal(Face &face, std::function< void()> f)
Invokes a callback when a face is closed.
Definition: channel.cpp:47
#define NFD_LOG_CHAN_DEBUG(msg)
Log a message at DEBUG level.
Definition: channel-log.hpp:49
optional< ssize_t > mtu
Definition: face-common.hpp:83
EthernetChannel-related error.
Copyright (c) 2011-2015 Regents of the University of California.
Definition: ndn-common.hpp:39
#define NFD_LOG_CHAN_INFO(msg)
Log a message at INFO level.
Definition: channel-log.hpp:52
#define NFD_LOG_CHAN_TRACE(msg)
Log a message at TRACE level.
Definition: channel-log.hpp:46
std::tuple< const ether_header *, std::string > checkFrameHeader(span< const uint8_t > packet, const Address &localAddr, const Address &destAddr)
#define NFD_LOG_CHAN_WARN(msg)
Log a message at WARN level.
Definition: channel-log.hpp:55
const size_t HDR_LEN
Total octets in Ethernet header (without 802.1Q tag)
Definition: ethernet.hpp:43
bool isListening() const final
Returns whether the channel is listening.
void listen(const FaceCreatedCallback &onFaceCreated, const FaceCreationFailedCallback &onFaceCreationFailed)
Start listening.
const uint16_t ETHERTYPE_NDN
Definition: ethernet.hpp:39
represents an Ethernet hardware address
Definition: ethernet.hpp:52
EthernetChannel(shared_ptr< const ndn::net::NetworkInterface > localEndpoint, time::nanoseconds idleTimeout)
Create an Ethernet channel on the given localEndpoint (network interface)
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
std::function< void(const shared_ptr< Face > &)> FaceCreatedCallback
Prototype for the callback that is invoked when a face is created (in response to an incoming connect...
Definition: channel.hpp:86
size_t getNDropped() const
Get the number of packets dropped by the kernel, as reported by libpcap.
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.
A unicast Transport that uses raw Ethernet II frames.
static FaceUri fromDev(const std::string &ifname)
create dev FaceUri from network device name
Definition: face-uri.cpp:170
boost::chrono::nanoseconds nanoseconds
Definition: time.hpp:50
Parameters used to set Transport properties or LinkService options on a newly created face...
Definition: face-common.hpp:78