NS-3 based Named Data Networking (NDN) simulator
ndnSIM 2.5: NDN, CCN, CCNx, content centric networks
API Documentation
udp-factory.cpp
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * Copyright (c) 2014-2021, 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 "udp-factory.hpp"
27 #include "generic-link-service.hpp"
29 #include "common/global.hpp"
30 
31 #include <boost/range/adaptor/map.hpp>
32 #include <boost/range/algorithm/copy.hpp>
33 
34 namespace nfd {
35 namespace face {
36 
37 namespace ip = boost::asio::ip;
38 namespace net = ndn::net;
39 
42 
43 const std::string&
45 {
46  static std::string id("udp");
47  return id;
48 }
49 
51  : ProtocolFactory(params)
52 {
53  m_netifAddConn = netmon->onInterfaceAdded.connect([this] (const auto& netif) {
54  this->applyMcastConfigToNetif(netif);
55  });
56 }
57 
58 void
59 UdpFactory::doProcessConfig(OptionalConfigSection configSection,
61 {
62  // udp
63  // {
64  // listen yes
65  // port 6363
66  // enable_v4 yes
67  // enable_v6 yes
68  // idle_timeout 600
69  // unicast_mtu 8800
70  // mcast yes
71  // mcast_group 224.0.23.170
72  // mcast_port 56363
73  // mcast_group_v6 ff02::1234
74  // mcast_port_v6 56363
75  // mcast_ad_hoc no
76  // whitelist
77  // {
78  // *
79  // }
80  // blacklist
81  // {
82  // }
83  // }
84 
85  m_wantCongestionMarking = context.generalConfig.wantCongestionMarking;
86 
87  bool wantListen = true;
88  uint16_t port = 6363;
89  bool enableV4 = false;
90  bool enableV6 = false;
91  uint32_t idleTimeout = 600;
92  size_t unicastMtu = ndn::MAX_NDN_PACKET_SIZE;
93  MulticastConfig mcastConfig;
94 
95  if (configSection) {
96  // These default to 'yes' but only if face_system.udp section is present
97  enableV4 = enableV6 = mcastConfig.isEnabled = true;
98 
99  for (const auto& pair : *configSection) {
100  const std::string& key = pair.first;
101  const ConfigSection& value = pair.second;
102 
103  if (key == "listen") {
104  wantListen = ConfigFile::parseYesNo(pair, "face_system.udp");
105  }
106  else if (key == "port") {
107  port = ConfigFile::parseNumber<uint16_t>(pair, "face_system.udp");
108  }
109  else if (key == "enable_v4") {
110  enableV4 = ConfigFile::parseYesNo(pair, "face_system.udp");
111  }
112  else if (key == "enable_v6") {
113  enableV6 = ConfigFile::parseYesNo(pair, "face_system.udp");
114  }
115  else if (key == "idle_timeout") {
116  idleTimeout = ConfigFile::parseNumber<uint32_t>(pair, "face_system.udp");
117  }
118  else if (key == "unicast_mtu") {
119  unicastMtu = ConfigFile::parseNumber<size_t>(pair, "face_system.udp");
120  ConfigFile::checkRange(unicastMtu, static_cast<size_t>(MIN_MTU), ndn::MAX_NDN_PACKET_SIZE,
121  "unicast_mtu", "face_system.udp");
122  }
123  else if (key == "keep_alive_interval") {
124  // ignored
125  }
126  else if (key == "mcast") {
127  mcastConfig.isEnabled = ConfigFile::parseYesNo(pair, "face_system.udp");
128  }
129  else if (key == "mcast_group") {
130  const std::string& valueStr = value.get_value<std::string>();
131  boost::system::error_code ec;
132  mcastConfig.group.address(ip::address_v4::from_string(valueStr, ec));
133  if (ec) {
134  NDN_THROW(ConfigFile::Error("face_system.udp.mcast_group: '" +
135  valueStr + "' cannot be parsed as an IPv4 address"));
136  }
137  else if (!mcastConfig.group.address().is_multicast()) {
138  NDN_THROW(ConfigFile::Error("face_system.udp.mcast_group: '" +
139  valueStr + "' is not a multicast address"));
140  }
141  }
142  else if (key == "mcast_port") {
143  mcastConfig.group.port(ConfigFile::parseNumber<uint16_t>(pair, "face_system.udp"));
144  }
145  else if (key == "mcast_group_v6") {
146  const std::string& valueStr = value.get_value<std::string>();
147  boost::system::error_code ec;
148  mcastConfig.groupV6.address(ip::address_v6::from_string(valueStr, ec));
149  if (ec) {
150  NDN_THROW(ConfigFile::Error("face_system.udp.mcast_group_v6: '" +
151  valueStr + "' cannot be parsed as an IPv6 address"));
152  }
153  else if (!mcastConfig.groupV6.address().is_multicast()) {
154  NDN_THROW(ConfigFile::Error("face_system.udp.mcast_group_v6: '" +
155  valueStr + "' is not a multicast address"));
156  }
157  }
158  else if (key == "mcast_port_v6") {
159  mcastConfig.groupV6.port(ConfigFile::parseNumber<uint16_t>(pair, "face_system.udp"));
160  }
161  else if (key == "mcast_ad_hoc") {
162  bool wantAdHoc = ConfigFile::parseYesNo(pair, "face_system.udp");
163  mcastConfig.linkType = wantAdHoc ? ndn::nfd::LINK_TYPE_AD_HOC : ndn::nfd::LINK_TYPE_MULTI_ACCESS;
164  }
165  else if (key == "whitelist") {
166  mcastConfig.netifPredicate.parseWhitelist(value);
167  }
168  else if (key == "blacklist") {
169  mcastConfig.netifPredicate.parseBlacklist(value);
170  }
171  else {
172  NDN_THROW(ConfigFile::Error("Unrecognized option face_system.udp." + key));
173  }
174  }
175 
176  if (!enableV4 && !enableV6 && !mcastConfig.isEnabled) {
178  "IPv4 and IPv6 UDP channels and UDP multicast have been disabled. "
179  "Remove face_system.udp section to disable UDP channels or enable at least one of them."));
180  }
181  }
182 
183  if (context.isDryRun) {
184  return;
185  }
186 
187  m_defaultUnicastMtu = unicastMtu;
188 
189  if (enableV4) {
190  udp::Endpoint endpoint(ip::udp::v4(), port);
191  shared_ptr<UdpChannel> v4Channel = this->createChannel(endpoint, time::seconds(idleTimeout));
192  if (wantListen && !v4Channel->isListening()) {
193  v4Channel->listen(this->addFace, nullptr);
194  }
195  providedSchemes.insert("udp");
196  providedSchemes.insert("udp4");
197  }
198  else if (providedSchemes.count("udp4") > 0) {
199  NFD_LOG_WARN("Cannot close udp4 channel after its creation");
200  }
201 
202  if (enableV6) {
203  udp::Endpoint endpoint(ip::udp::v6(), port);
204  shared_ptr<UdpChannel> v6Channel = this->createChannel(endpoint, time::seconds(idleTimeout));
205  if (wantListen && !v6Channel->isListening()) {
206  v6Channel->listen(this->addFace, nullptr);
207  }
208  providedSchemes.insert("udp");
209  providedSchemes.insert("udp6");
210  }
211  else if (providedSchemes.count("udp6") > 0) {
212  NFD_LOG_WARN("Cannot close udp6 channel after its creation");
213  }
214 
215  if (m_mcastConfig.isEnabled != mcastConfig.isEnabled) {
216  if (mcastConfig.isEnabled) {
217  NFD_LOG_INFO("enabling multicast on " << mcastConfig.group);
218  NFD_LOG_INFO("enabling multicast on " << mcastConfig.groupV6);
219  }
220  else {
221  NFD_LOG_INFO("disabling multicast");
222  }
223  }
224  else if (mcastConfig.isEnabled) {
225  if (m_mcastConfig.linkType != mcastConfig.linkType && !m_mcastFaces.empty()) {
226  NFD_LOG_WARN("Cannot change ad hoc setting on existing faces");
227  }
228  if (m_mcastConfig.group != mcastConfig.group) {
229  NFD_LOG_INFO("changing IPv4 multicast group from " << m_mcastConfig.group <<
230  " to " << mcastConfig.group);
231  }
232  if (m_mcastConfig.groupV6 != mcastConfig.groupV6) {
233  NFD_LOG_INFO("changing IPv6 multicast group from " << m_mcastConfig.groupV6 <<
234  " to " << mcastConfig.groupV6);
235  }
236  if (m_mcastConfig.netifPredicate != mcastConfig.netifPredicate) {
237  NFD_LOG_INFO("changing whitelist/blacklist");
238  }
239  }
240 
241  // Even if there's no configuration change, we still need to re-apply configuration because
242  // netifs may have changed.
243  m_mcastConfig = mcastConfig;
244  this->applyMcastConfig(context);
245 }
246 
247 void
248 UdpFactory::doCreateFace(const CreateFaceRequest& req,
249  const FaceCreatedCallback& onCreated,
250  const FaceCreationFailedCallback& onFailure)
251 {
252  if (req.localUri) {
253  NFD_LOG_TRACE("Cannot create unicast UDP face with LocalUri");
254  onFailure(406, "Unicast UDP faces cannot be created with a LocalUri");
255  return;
256  }
257 
259  NFD_LOG_TRACE("createFace does not support FACE_PERSISTENCY_ON_DEMAND");
260  onFailure(406, "Outgoing UDP faces do not support on-demand persistency");
261  return;
262  }
263 
264  udp::Endpoint endpoint(ip::address::from_string(req.remoteUri.getHost()),
265  boost::lexical_cast<uint16_t>(req.remoteUri.getPort()));
266 
267  if (endpoint.address().is_multicast()) {
268  NFD_LOG_TRACE("createFace does not support multicast faces");
269  onFailure(406, "Cannot create multicast UDP faces");
270  return;
271  }
272 
273  if (req.params.wantLocalFields) {
274  // UDP faces are never local
275  NFD_LOG_TRACE("createFace cannot create non-local face with local fields enabled");
276  onFailure(406, "Local fields can only be enabled on faces with local scope");
277  return;
278  }
279 
280  if (req.params.mtu && *req.params.mtu < MIN_MTU) {
281  // The specified MTU must be greater than the minimum possible
282  NFD_LOG_TRACE("createFace: override MTU cannot be less than " << MIN_MTU);
283  onFailure(406, "Override MTU cannot be less than " + to_string(MIN_MTU));
284  return;
285  }
286 
287  // very simple logic for now
288  for (const auto& i : m_channels) {
289  if ((i.first.address().is_v4() && endpoint.address().is_v4()) ||
290  (i.first.address().is_v6() && endpoint.address().is_v6())) {
291  i.second->connect(endpoint, req.params, onCreated, onFailure);
292  return;
293  }
294  }
295 
296  NFD_LOG_TRACE("No channels available to connect to " << endpoint);
297  onFailure(504, "No channels available to connect");
298 }
299 
300 shared_ptr<UdpChannel>
302  time::nanoseconds idleTimeout)
303 {
304  auto it = m_channels.find(localEndpoint);
305  if (it != m_channels.end())
306  return it->second;
307 
308  // check if the endpoint is already used by a multicast face
309  if (m_mcastFaces.find(localEndpoint) != m_mcastFaces.end()) {
310  NDN_THROW(Error("Cannot create UDP channel on " + boost::lexical_cast<std::string>(localEndpoint) +
311  ", endpoint already allocated to a UDP multicast face"));
312  }
313 
314  auto channel = std::make_shared<UdpChannel>(localEndpoint, idleTimeout,
315  m_wantCongestionMarking, m_defaultUnicastMtu);
316  m_channels[localEndpoint] = channel;
317  return channel;
318 }
319 
320 std::vector<shared_ptr<const Channel>>
321 UdpFactory::doGetChannels() const
322 {
323  return getChannelsFromMap(m_channels);
324 }
325 
326 shared_ptr<Face>
327 UdpFactory::createMulticastFace(const shared_ptr<const net::NetworkInterface>& netif,
328  const ip::address& localAddress,
329  const udp::Endpoint& multicastEndpoint)
330 {
331  BOOST_ASSERT(multicastEndpoint.address().is_multicast());
332 
333  udp::Endpoint localEp(localAddress, multicastEndpoint.port());
334  BOOST_ASSERT(localEp.protocol() == multicastEndpoint.protocol());
335 
336  auto mcastEp = multicastEndpoint;
337  if (mcastEp.address().is_v6()) {
338  // in IPv6, a scope id on the multicast address is always required
339  auto mcastAddress = mcastEp.address().to_v6();
340  mcastAddress.scope_id(netif->getIndex());
341  mcastEp.address(mcastAddress);
342  }
343 
344  // check if the local endpoint is already used by another multicast face
345  auto it = m_mcastFaces.find(localEp);
346  if (it != m_mcastFaces.end()) {
347  if (it->second->getRemoteUri() == FaceUri(mcastEp))
348  return it->second;
349  else
350  NDN_THROW(Error("Cannot create UDP multicast face on " + boost::lexical_cast<std::string>(localEp) +
351  ", endpoint already allocated to a different UDP multicast face"));
352  }
353 
354  // check if the local endpoint is already used by a unicast channel
355  if (m_channels.find(localEp) != m_channels.end()) {
356  NDN_THROW(Error("Cannot create UDP multicast face on " + boost::lexical_cast<std::string>(localEp) +
357  ", endpoint already allocated to a UDP channel"));
358  }
359 
361  MulticastUdpTransport::openRxSocket(rxSock, mcastEp, localAddress, netif);
363  MulticastUdpTransport::openTxSocket(txSock, udp::Endpoint(localAddress, 0), netif);
364 
365  GenericLinkService::Options options;
366  options.allowCongestionMarking = m_wantCongestionMarking;
367  auto linkService = make_unique<GenericLinkService>(options);
368  auto transport = make_unique<MulticastUdpTransport>(mcastEp, std::move(rxSock), std::move(txSock),
369  m_mcastConfig.linkType);
370  auto face = make_shared<Face>(std::move(linkService), std::move(transport));
371 
372  m_mcastFaces[localEp] = face;
373  connectFaceClosedSignal(*face, [this, localEp] { m_mcastFaces.erase(localEp); });
374 
375  // Associate with the first available channel of the same protocol family
376  auto channelIt = std::find_if(m_channels.begin(), m_channels.end(),
377  [isV4 = localEp.address().is_v4()] (const auto& it) {
378  return it.first.address().is_v4() == isV4;
379  });
380  face->setChannel(channelIt != m_channels.end() ? channelIt->second : nullptr);
381 
382  return face;
383 }
384 
385 static optional<ip::address>
387 {
388  for (const auto& na : netif.getNetworkAddresses()) {
389  if (na.getFamily() == af &&
390  (na.getScope() == net::AddressScope::LINK || na.getScope() == net::AddressScope::GLOBAL)) {
391  return na.getIp();
392  }
393  }
394  return nullopt;
395 }
396 
397 std::vector<shared_ptr<Face>>
398 UdpFactory::applyMcastConfigToNetif(const shared_ptr<const net::NetworkInterface>& netif)
399 {
400  BOOST_ASSERT(netif != nullptr);
401 
402  if (!m_mcastConfig.isEnabled) {
403  return {};
404  }
405 
406  if (!netif->isUp()) {
407  NFD_LOG_DEBUG("Not creating multicast faces on " << netif->getName() << ": netif is down");
408  return {};
409  }
410 
411  if (netif->isLoopback()) {
412  NFD_LOG_DEBUG("Not creating multicast faces on " << netif->getName() << ": netif is loopback");
413  return {};
414  }
415 
416  if (!netif->canMulticast()) {
417  NFD_LOG_DEBUG("Not creating multicast faces on " << netif->getName() << ": netif cannot multicast");
418  return {};
419  }
420 
421  if (!m_mcastConfig.netifPredicate(*netif)) {
422  NFD_LOG_DEBUG("Not creating multicast faces on " << netif->getName() << ": rejected by whitelist/blacklist");
423  return {};
424  }
425 
426  std::vector<ip::address> addrs;
427  for (auto af : {net::AddressFamily::V4, net::AddressFamily::V6}) {
428  auto addr = pickAddress(*netif, af);
429  if (addr)
430  addrs.push_back(*addr);
431  }
432 
433  if (addrs.empty()) {
434  NFD_LOG_DEBUG("Not creating multicast faces on " << netif->getName() << ": no viable IP address");
435  // keep an eye on new addresses
436  m_netifConns[netif->getIndex()].addrAddConn =
437  netif->onAddressAdded.connect([=] (auto&&...) { this->applyMcastConfigToNetif(netif); });
438  return {};
439  }
440 
441  NFD_LOG_DEBUG("Creating multicast faces on " << netif->getName());
442 
443  std::vector<shared_ptr<Face>> faces;
444  for (const auto& addr : addrs) {
445  auto face = this->createMulticastFace(netif, addr,
446  addr.is_v4() ? m_mcastConfig.group : m_mcastConfig.groupV6);
447  if (face->getId() == INVALID_FACEID) {
448  // new face: register with forwarding
449  this->addFace(face);
450  }
451  faces.push_back(std::move(face));
452  }
453 
454  return faces;
455 }
456 
457 void
458 UdpFactory::applyMcastConfig(const FaceSystem::ConfigContext&)
459 {
460  // collect old faces
461  std::set<shared_ptr<Face>> facesToClose;
462  boost::copy(m_mcastFaces | boost::adaptors::map_values,
463  std::inserter(facesToClose, facesToClose.end()));
464 
465  // create faces if requested by config
466  for (const auto& netif : netmon->listNetworkInterfaces()) {
467  auto facesToKeep = this->applyMcastConfigToNetif(netif);
468  for (const auto& face : facesToKeep) {
469  // don't destroy face
470  facesToClose.erase(face);
471  }
472  }
473 
474  // destroy old faces that are not needed in new configuration
475  for (const auto& face : facesToClose) {
476  face->close();
477  }
478 }
479 
480 } // namespace face
481 } // namespace nfd
std::set< std::string > providedSchemes
FaceUri schemes provided by this protocol factory.
shared_ptr< Face > createMulticastFace(const shared_ptr< const ndn::net::NetworkInterface > &netif, const boost::asio::ip::address &localAddress, const udp::Endpoint &multicastEndpoint)
Create a multicast UDP face.
boost::chrono::seconds seconds
Definition: time.hpp:47
static void openRxSocket(protocol::socket &sock, const protocol::endpoint &multicastGroup, const boost::asio::ip::address &localAddress, const shared_ptr< const ndn::net::NetworkInterface > &netif=nullptr)
const std::string & getHost() const
get host (domain)
Definition: face-uri.hpp:116
static bool parseYesNo(const ConfigSection &node, const std::string &key, const std::string &sectionName)
parse a config option that can be either "yes" or "no"
Definition: config-file.cpp:60
shared_ptr< ndn::net::NetworkMonitor > netmon
NetworkMonitor for listing available network interfaces and monitoring their changes.
#define NFD_LOG_INIT(name)
Definition: logger.hpp:31
std::string to_string(const T &val)
Definition: backports.hpp:86
static void checkRange(T value, T min, T max, const std::string &key, const std::string &sectionName)
check that a value is within the inclusive range [min, max]
static optional< ip::address > pickAddress(const net::NetworkInterface &netif, net::AddressFamily af)
ndn::nfd::FacePersistency persistency
Definition: face-common.hpp:80
const std::string & getPort() const
get port
Definition: face-uri.hpp:123
detail::SimulatorIo & getGlobalIoService()
Returns the global io_service instance for the calling thread.
Definition: global.cpp:49
NFD_REGISTER_PROTOCOL_FACTORY(EthernetFactory)
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
boost::optional< const ConfigSection & > OptionalConfigSection
an optional config file section
Definition: config-file.hpp:41
Protocol factory for UDP over IPv4 and IPv6.
Definition: udp-factory.hpp:37
void connectFaceClosedSignal(Face &face, std::function< void()> f)
Invokes a callback when a face is closed.
Definition: channel.cpp:47
#define NDN_THROW(e)
Definition: exception.hpp:61
FaceCreatedCallback addFace
callback when a new face is created
Represents one network interface attached to the host.
#define NFD_LOG_INFO
Definition: logger.hpp:39
Provides support for an underlying protocol.
optional< ssize_t > mtu
Definition: face-common.hpp:83
Copyright (c) 2011-2015 Regents of the University of California.
Definition: ndn-common.hpp:39
static void openTxSocket(protocol::socket &sock, const protocol::endpoint &localEndpoint, const shared_ptr< const ndn::net::NetworkInterface > &netif=nullptr, bool enableLoopback=false)
#define NFD_LOG_DEBUG
Definition: logger.hpp:38
#define NFD_LOG_TRACE
Definition: logger.hpp:37
shared_ptr< UdpChannel > createChannel(const udp::Endpoint &localEndpoint, time::nanoseconds idleTimeout)
Create UDP-based channel using udp::Endpoint.
Parameters to ProtocolFactory constructor.
boost::property_tree::ptree ConfigSection
a config file section
represents the underlying protocol and address used by a Face
Definition: face-uri.hpp:44
context for processing a config section in ProtocolFactory
Definition: face-system.hpp:96
boost::asio::ip::udp::endpoint Endpoint
#define NFD_LOG_WARN
Definition: logger.hpp:40
static const std::string & getId() noexcept
Definition: udp-factory.cpp:44
Encapsulates a face creation request and all its parameters.
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
const ssize_t MIN_MTU
Minimum MTU that may be set.
Definition: face-common.hpp:61
static std::vector< shared_ptr< const Channel > > getChannelsFromMap(const ChannelMap &channelMap)
Catch-all error for socket component errors that don&#39;t fit in other categories.
Definition: base.hpp:83
const std::set< NetworkAddress > & getNetworkAddresses() const
Returns a list of all network-layer addresses present on the interface.
const FaceId INVALID_FACEID
indicates an invalid FaceId
Definition: face-common.hpp:47
const nullopt_t nullopt((nullopt_t::init()))
UdpFactory(const CtorParams &params)
Definition: udp-factory.cpp:50
boost::chrono::nanoseconds nanoseconds
Definition: time.hpp:50
const size_t MAX_NDN_PACKET_SIZE
Practical size limit of a network-layer packet.
Definition: tlv.hpp:41