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-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-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) {
115  if (error != boost::asio::error::operation_aborted) {
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  const uint8_t* pkt;
124  size_t len;
125  std::string err;
126  std::tie(pkt, len, err) = m_pcap.readNextPacket();
127 
128  if (pkt == nullptr) {
129  NFD_LOG_CHAN_WARN("Read error: " << err);
130  }
131  else {
132  const ether_header* eh;
133  std::tie(eh, err) = ethernet::checkFrameHeader(pkt, len, m_localEndpoint->getEthernetAddress(),
134  m_localEndpoint->getEthernetAddress());
135  if (eh == nullptr) {
136  NFD_LOG_CHAN_DEBUG(err);
137  }
138  else {
139  ethernet::Address sender(eh->ether_shost);
140  pkt += ethernet::HDR_LEN;
141  len -= ethernet::HDR_LEN;
142  processIncomingPacket(pkt, len, sender, onFaceCreated, onReceiveFailed);
143  }
144  }
145 
146 #ifdef _DEBUG
147  size_t nDropped = m_pcap.getNDropped();
148  if (nDropped - m_nDropped > 0)
149  NFD_LOG_CHAN_DEBUG("Detected " << nDropped - m_nDropped << " dropped frame(s)");
150  m_nDropped = nDropped;
151 #endif
152 
153  asyncRead(onFaceCreated, onReceiveFailed);
154 }
155 
156 void
157 EthernetChannel::processIncomingPacket(const uint8_t* packet, size_t length,
158  const ethernet::Address& sender,
159  const FaceCreatedCallback& onFaceCreated,
160  const FaceCreationFailedCallback& onReceiveFailed)
161 {
162  NFD_LOG_CHAN_TRACE("New peer " << sender);
163 
164  bool isCreated = false;
165  shared_ptr<Face> face;
166  try {
167  FaceParams params;
168  params.persistency = ndn::nfd::FACE_PERSISTENCY_ON_DEMAND;
169  std::tie(isCreated, face) = createFace(sender, params);
170  }
171  catch (const EthernetTransport::Error& e) {
172  NFD_LOG_CHAN_DEBUG("Face creation for " << sender << " failed: " << e.what());
173  if (onReceiveFailed)
174  onReceiveFailed(504, "Face creation failed: "s + e.what());
175  return;
176  }
177 
178  if (isCreated)
179  onFaceCreated(face);
180  else
181  NFD_LOG_CHAN_DEBUG("Received frame for existing face");
182 
183  // dispatch the packet to the face for processing
184  auto* transport = static_cast<UnicastEthernetTransport*>(face->getTransport());
185  transport->receivePayload(packet, length, sender);
186 }
187 
188 std::pair<bool, shared_ptr<Face>>
189 EthernetChannel::createFace(const ethernet::Address& remoteEndpoint,
190  const FaceParams& params)
191 {
192  auto it = m_channelFaces.find(remoteEndpoint);
193  if (it != m_channelFaces.end()) {
194  // we already have a face for this endpoint, so reuse it
195  NFD_LOG_CHAN_TRACE("Reusing existing face for " << remoteEndpoint);
196  return {false, it->second};
197  }
198 
199  // else, create a new face
200  GenericLinkService::Options options;
201  options.allowFragmentation = true;
202  options.allowReassembly = true;
203  options.reliabilityOptions.isEnabled = params.wantLpReliability;
204 
205  auto linkService = make_unique<GenericLinkService>(options);
206  auto transport = make_unique<UnicastEthernetTransport>(*m_localEndpoint, remoteEndpoint,
207  params.persistency, m_idleFaceTimeout,
208  params.mtu);
209  auto face = make_shared<Face>(std::move(linkService), std::move(transport));
210 
211  m_channelFaces[remoteEndpoint] = face;
212  connectFaceClosedSignal(*face, [this, remoteEndpoint] {
213  m_channelFaces.erase(remoteEndpoint);
214  updateFilter();
215  });
216  updateFilter();
217 
218  return {true, face};
219 }
220 
221 void
222 EthernetChannel::updateFilter()
223 {
224  if (!isListening())
225  return;
226 
227  std::string filter = "(ether proto " + to_string(ethernet::ETHERTYPE_NDN) +
228  ") && (ether dst " + m_localEndpoint->getEthernetAddress().toString() + ")";
229  for (const auto& addr : m_channelFaces | boost::adaptors::map_keys) {
230  filter += " && (not ether src " + addr.toString() + ")";
231  }
232  // "not vlan" must appear last in the filter expression, or the
233  // rest of the filter won't work as intended, see pcap-filter(7)
234  filter += " && (not vlan)";
235 
236  NFD_LOG_CHAN_TRACE("Updating filter: " << filter);
237  m_pcap.setPacketFilter(filter.data());
238 }
239 
240 } // namespace face
241 } // namespace nfd
ethernet-channel.hpp
global.hpp
nfd::face::EthernetChannel::listen
void listen(const FaceCreatedCallback &onFaceCreated, const FaceCreationFailedCallback &onFaceCreationFailed)
Start listening.
Definition: ethernet-channel.cpp:79
nfd::face::EthernetChannel::EthernetChannel
EthernetChannel(shared_ptr< const ndn::net::NetworkInterface > localEndpoint, time::nanoseconds idleTimeout)
Create an Ethernet channel on the given localEndpoint (network interface)
Definition: ethernet-channel.cpp:41
nonstd::optional_lite::std11::move
T & move(T &t)
Definition: optional.hpp:421
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::ethernet::Address
represents an Ethernet hardware address
Definition: ethernet.hpp:53
ethernet-protocol.hpp
ndn::ethernet::ETHERTYPE_NDN
const uint16_t ETHERTYPE_NDN
Definition: ethernet.hpp:39
nfd::face::EthernetChannel
Class implementing Ethernet-based channel to create faces.
Definition: ethernet-channel.hpp:41
NDN_THROW_NESTED
#define NDN_THROW_NESTED(e)
Definition: exception.hpp:71
NFD_LOG_CHAN_DEBUG
#define NFD_LOG_CHAN_DEBUG(msg)
Log a message at DEBUG level.
Definition: channel-log.hpp:49
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
Copyright (c) 2011-2015 Regents of the University of California.
Definition: ndn-common.hpp:40
NFD_LOG_CHAN_INFO
#define NFD_LOG_CHAN_INFO(msg)
Log a message at INFO level.
Definition: channel-log.hpp:52
unicast-ethernet-transport.hpp
NFD_LOG_CHAN_WARN
#define NFD_LOG_CHAN_WARN(msg)
Log a message at WARN level.
Definition: channel-log.hpp:55
ndn::FaceUri::fromDev
static FaceUri fromDev(const std::string &ifname)
create dev FaceUri from network device name
Definition: face-uri.cpp:169
NFD_LOG_CHAN_TRACE
#define NFD_LOG_CHAN_TRACE(msg)
Log a message at TRACE level.
Definition: channel-log.hpp:46
nfd::face::EthernetChannel::Error
EthernetChannel-related error.
Definition: ethernet-channel.hpp:47
ndn::ethernet::HDR_LEN
const size_t HDR_LEN
Total octets in Ethernet header (without 802.1Q tag)
Definition: ethernet.hpp:43
nfd::face::EthernetChannel::isListening
bool isListening() const override
Returns whether the channel is listening.
Definition: ethernet-channel.hpp:66
nfd::face::connectFaceClosedSignal
void connectFaceClosedSignal(Face &face, std::function< void()> f)
Invokes a callback when a face is closed.
Definition: channel.cpp:41
nfd::face::UnicastEthernetTransport
UnicastEthernetTransport
Definition: unicast-ethernet-transport.cpp:34
nfd::face::PcapHelper::activate
void activate(int dlt)
Start capturing packets.
Definition: pcap-helper.cpp:64
nfd::face::FaceCreatedCallback
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:74
ndn::nfd::FACE_PERSISTENCY_ON_DEMAND
@ FACE_PERSISTENCY_ON_DEMAND
face is on-demand
Definition: nfd-constants.hpp:48
face.hpp
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::FaceParams
Parameters used to set Transport properties or LinkService options on a newly created face.
Definition: face-common.hpp:73
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::Channel::setUri
void setUri(const FaceUri &uri)
Definition: channel.cpp:35
nfd::face::PcapHelper::setPacketFilter
void setPacketFilter(const char *filter) const
Install a BPF filter on the receiving socket.
Definition: pcap-helper.cpp:115
nfd::face::EthernetChannel::connect
void connect(const ethernet::Address &remoteEndpoint, const FaceParams &params, const FaceCreatedCallback &onFaceCreated, const FaceCreationFailedCallback &onConnectFailed)
Create a unicast Ethernet face toward remoteEndpoint.
Definition: ethernet-channel.cpp:57
nfd::face::FaceCreationFailedCallback
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:78
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