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