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