nlsr.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, The University of Memphis,
4  * Regents of the University of California,
5  * Arizona Board of Regents.
6  *
7  * This file is part of NLSR (Named-data Link State Routing).
8  * See AUTHORS.md for complete list of NLSR authors and contributors.
9  *
10  * NLSR is free software: you can redistribute it and/or modify it under the terms
11  * of the GNU General Public License as published by the Free Software Foundation,
12  * either version 3 of the License, or (at your option) any later version.
13  *
14  * NLSR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
15  * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
16  * PURPOSE. See the GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along with
19  * NLSR, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
20  */
21 
22 #include "nlsr.hpp"
23 #include "adjacent.hpp"
24 #include "logger.hpp"
25 
26 #include <cstdlib>
27 #include <cstdio>
28 #include <unistd.h>
29 
30 #include <ndn-cxx/net/face-uri.hpp>
31 
32 namespace nlsr {
33 
34 INIT_LOGGER(Nlsr);
35 
36 const ndn::Name Nlsr::LOCALHOST_PREFIX = ndn::Name("/localhost/nlsr");
37 
38 Nlsr::Nlsr(ndn::Face& face, ndn::KeyChain& keyChain, ConfParameter& confParam)
39  : m_face(face)
40  , m_scheduler(face.getIoService())
41  , m_confParam(confParam)
42  , m_adjacencyList(confParam.getAdjacencyList())
43  , m_namePrefixList(confParam.getNamePrefixList())
44  , m_fib(m_face, m_scheduler, m_adjacencyList, m_confParam, keyChain)
45  , m_routingTable(m_scheduler, m_fib, m_lsdb, m_namePrefixTable, m_confParam)
46  , m_namePrefixTable(m_fib, m_routingTable, m_routingTable.afterRoutingChange)
47  , m_lsdb(m_face, keyChain, m_confParam, m_namePrefixTable, m_routingTable)
48  , m_helloProtocol(m_face, keyChain, confParam, m_routingTable, m_lsdb)
49  , m_onNewLsaConnection(m_lsdb.getSync().onNewLsa->connect(
50  [this] (const ndn::Name& updateName, uint64_t sequenceNumber,
51  const ndn::Name& originRouter) {
52  registerStrategyForCerts(originRouter);
53  }))
54  , m_onPrefixRegistrationSuccess(m_fib.onPrefixRegistrationSuccess.connect(
55  [this] (const ndn::Name& name) {
56  m_helloProtocol.sendHelloInterest(name);
57  }))
58  , m_onHelloDataValidated(m_helloProtocol.onHelloDataValidated.connect(
59  [this] (const ndn::Name& neighbor) {
60  auto it = m_adjacencyList.findAdjacent(neighbor);
61  if (it != m_adjacencyList.end()) {
62  m_fib.registerPrefix(m_confParam.getSyncPrefix(), it->getFaceUri(), it->getLinkCost(),
63  ndn::time::milliseconds::max(), ndn::nfd::ROUTE_FLAG_CAPTURE, 0);
64  }
65  }))
66  , m_dispatcher(m_face, keyChain)
67  , m_datasetHandler(m_dispatcher, m_lsdb, m_routingTable)
68  , m_controller(m_face, keyChain)
69  , m_faceDatasetController(m_face, keyChain)
70  , m_prefixUpdateProcessor(m_dispatcher,
71  m_confParam.getPrefixUpdateValidator(),
72  m_namePrefixList,
73  m_lsdb,
74  m_confParam.getConfFileNameDynamic())
75  , m_nfdRibCommandProcessor(m_dispatcher,
76  m_namePrefixList,
77  m_lsdb)
78  , m_statsCollector(m_lsdb, m_helloProtocol)
79  , m_faceMonitor(m_face)
80 {
81  NLSR_LOG_DEBUG("Initializing Nlsr");
82 
83  m_faceMonitor.onNotification.connect(std::bind(&Nlsr::onFaceEventNotification, this, _1));
84  m_faceMonitor.start();
85 
86  // Do key initialization and registrations first, then initialize faces
87  // which will create routes to neighbor
88 
89  setStrategies();
90 
91  NLSR_LOG_DEBUG("Default NLSR identity: " << m_confParam.getSigningInfo().getSignerName());
92 
93  // Can be moved to Lsdb ctor
94  setLsaInterestFilter();
95 
96  // Add top-level prefixes: router and localhost prefix
97  addDispatcherTopPrefix(ndn::Name(m_confParam.getRouterPrefix()).append("nlsr"));
98  addDispatcherTopPrefix(LOCALHOST_PREFIX);
99 
100  enableIncomingFaceIdIndication();
101 
102  registerLocalhostPrefix();
103  registerRouterPrefix();
104 
105  initializeFaces(std::bind(&Nlsr::processFaceDataset, this, _1),
106  std::bind(&Nlsr::onFaceDatasetFetchTimeout, this, _1, _2, 0));
107 
108  // Could be moved into ctor, but unit tests need to be modified
109  initialize();
110 }
111 
112 void
113 Nlsr::registerStrategyForCerts(const ndn::Name& originRouter)
114 {
115  for (const ndn::Name& router : m_strategySetOnRouters) {
116  if (router == originRouter) {
117  // Have already set strategy for this router's certs once
118  return;
119  }
120  }
121 
122  m_strategySetOnRouters.push_back(originRouter);
123 
124  ndn::Name routerKey(originRouter);
125  routerKey.append(ndn::security::Certificate::KEY_COMPONENT);
126  ndn::Name instanceKey(originRouter);
127  instanceKey.append("nlsr").append(ndn::security::Certificate::KEY_COMPONENT);
128 
129  m_fib.setStrategy(routerKey, Fib::BEST_ROUTE_V2_STRATEGY, 0);
130  m_fib.setStrategy(instanceKey, Fib::BEST_ROUTE_V2_STRATEGY, 0);
131 
132  ndn::Name siteKey;
133  for (size_t i = 0; i < originRouter.size(); ++i) {
134  if (originRouter[i].toUri() == "%C1.Router") {
135  break;
136  }
137  siteKey.append(originRouter[i]);
138  }
139  ndn::Name opPrefix(siteKey);
140  siteKey.append(ndn::security::Certificate::KEY_COMPONENT);
141  m_fib.setStrategy(siteKey, Fib::BEST_ROUTE_V2_STRATEGY, 0);
142 
143  opPrefix.append(std::string("%C1.Operator"));
144  m_fib.setStrategy(opPrefix, Fib::BEST_ROUTE_V2_STRATEGY, 0);
145 }
146 
147 void
148 Nlsr::registrationFailed(const ndn::Name& name)
149 {
150  NLSR_LOG_ERROR("ERROR: Failed to register prefix " << name << " in local hub's daemon");
151  NDN_THROW(Error("Error: Prefix registration failed"));
152 }
153 
154 void
155 Nlsr::onRegistrationSuccess(const ndn::Name& name)
156 {
157  NLSR_LOG_DEBUG("Successfully registered prefix: " << name);
158 }
159 
160 void
161 Nlsr::setLsaInterestFilter()
162 {
163  ndn::Name name = m_confParam.getLsaPrefix();
164 
165  NLSR_LOG_DEBUG("Setting interest filter for LsaPrefix: " << name);
166 
167  m_face.setInterestFilter(ndn::InterestFilter(name).allowLoopback(false),
168  std::bind(&Lsdb::processInterest, &m_lsdb, _1, _2),
169  std::bind(&Nlsr::onRegistrationSuccess, this, _1),
170  std::bind(&Nlsr::registrationFailed, this, _1),
171  m_confParam.getSigningInfo(), ndn::nfd::ROUTE_FLAG_CAPTURE);
172 }
173 
174 void
175 Nlsr::addDispatcherTopPrefix(const ndn::Name& topPrefix)
176 {
177  try {
178  // false since we want to have control over the registration process
179  m_dispatcher.addTopPrefix(topPrefix, false, m_confParam.getSigningInfo());
180  }
181  catch (const std::exception& e) {
182  NLSR_LOG_ERROR("Error setting top-level prefix in dispatcher: " << e.what() << "\n");
183  }
184 }
185 
186 void
187 Nlsr::setStrategies()
188 {
189  m_fib.setStrategy(m_confParam.getLsaPrefix(), Fib::MULTICAST_STRATEGY, 0);
190  m_fib.setStrategy(m_confParam.getSyncPrefix(), Fib::MULTICAST_STRATEGY, 0);
191 }
192 
193 void
194 Nlsr::initialize()
195 {
196  // Logging start
197  m_adjacencyList.writeLog();
198  NLSR_LOG_DEBUG(m_namePrefixList);
199 
200  m_lsdb.buildAndInstallOwnNameLsa();
201 
202  // Install coordinate LSAs if using HR or dry-run HR.
203  if (m_confParam.getHyperbolicState() != HYPERBOLIC_STATE_OFF) {
204  m_lsdb.buildAndInstallOwnCoordinateLsa();
205  }
206 
207  // Need to set direct neighbors' costs to 0 for hyperbolic routing
208  if (m_confParam.getHyperbolicState() == HYPERBOLIC_STATE_ON) {
209  for (auto&& neighbor : m_adjacencyList.getAdjList()) {
210  neighbor.setLinkCost(0);
211  }
212  }
213 }
214 
215 void
216 Nlsr::registerLocalhostPrefix()
217 {
218  m_face.registerPrefix(LOCALHOST_PREFIX,
219  std::bind(&Nlsr::onRegistrationSuccess, this, _1),
220  std::bind(&Nlsr::registrationFailed, this, _1));
221 }
222 
223 void
224 Nlsr::registerRouterPrefix()
225 {
226  m_face.registerPrefix(ndn::Name(m_confParam.getRouterPrefix()).append("nlsr"),
227  std::bind(&Nlsr::onRegistrationSuccess, this, _1),
228  std::bind(&Nlsr::registrationFailed, this, _1));
229 }
230 
231 void
232 Nlsr::onFaceEventNotification(const ndn::nfd::FaceEventNotification& faceEventNotification)
233 {
234  NLSR_LOG_TRACE("onFaceEventNotification called");
235 
236  switch (faceEventNotification.getKind()) {
237  case ndn::nfd::FACE_EVENT_DESTROYED: {
238  uint64_t faceId = faceEventNotification.getFaceId();
239 
240  auto adjacent = m_adjacencyList.findAdjacent(faceId);
241 
242  if (adjacent != m_adjacencyList.end()) {
243  NLSR_LOG_DEBUG("Face to " << adjacent->getName() << " with face id: " << faceId << " destroyed");
244 
245  adjacent->setFaceId(0);
246 
247  // Only trigger an Adjacency LSA build if this node is changing
248  // from ACTIVE to INACTIVE since this rebuild will effectively
249  // cancel the previous Adjacency LSA refresh event and schedule
250  // a new one further in the future.
251  //
252  // Continuously scheduling the refresh in the future will block
253  // the router from refreshing its Adjacency LSA. Since other
254  // routers' Name prefixes' expiration times are updated when
255  // this router refreshes its Adjacency LSA, the other routers'
256  // prefixes will expire and be removed from the RIB.
257  //
258  // This check is required to fix Bug #2733 for now. This check
259  // would be unnecessary to fix Bug #2733 when Issue #2732 is
260  // completed, but the check also helps with optimization so it
261  // can remain even when Issue #2732 is implemented.
262  if (adjacent->getStatus() == Adjacent::STATUS_ACTIVE) {
263  adjacent->setStatus(Adjacent::STATUS_INACTIVE);
264 
265  // A new adjacency LSA cannot be built until the neighbor is marked INACTIVE and
266  // has met the HELLO retry threshold
267  adjacent->setInterestTimedOutNo(m_confParam.getInterestRetryNumber());
268 
269  if (m_confParam.getHyperbolicState() == HYPERBOLIC_STATE_ON) {
270  m_routingTable.scheduleRoutingTableCalculation();
271  }
272  else {
273  // Will call scheduleRoutingTableCalculation internally
274  // if needed in case of LS or DRY_RUN
275  m_lsdb.scheduleAdjLsaBuild();
276  }
277  }
278  }
279  break;
280  }
281  case ndn::nfd::FACE_EVENT_CREATED: {
282  // Find the neighbor in our adjacency list
283  ndn::FaceUri faceUri;
284  try {
285  faceUri = ndn::FaceUri(faceEventNotification.getRemoteUri());
286  }
287  catch (const std::exception& e) {
288  NLSR_LOG_WARN(e.what());
289  return;
290  }
291  auto adjacent = m_adjacencyList.findAdjacent(faceUri);
292  uint64_t faceId = faceEventNotification.getFaceId();
293 
294  // If we have a neighbor by that FaceUri and it has no FaceId or
295  // the FaceId is different from ours, we have a match.
296  if (adjacent != m_adjacencyList.end() &&
297  (adjacent->getFaceId() == 0 || adjacent->getFaceId() != faceId))
298  {
299  NLSR_LOG_DEBUG("Face creation event matches neighbor: " << adjacent->getName()
300  << ". New Face ID: " << faceId << ". Registering prefixes.");
301  adjacent->setFaceId(faceId);
302 
303  registerAdjacencyPrefixes(*adjacent, ndn::time::milliseconds::max());
304 
305  // We should not do scheduleRoutingTableCalculation or scheduleAdjLsaBuild here
306  // because once the prefixes are registered, we send a HelloInterest
307  // to the prefix (see NLSR ctor). HelloProtocol will call these functions
308  // once HelloData is received and validated.
309  }
310  break;
311  }
312  default:
313  break;
314  }
315 }
316 
317 void
318 Nlsr::initializeFaces(const FetchDatasetCallback& onFetchSuccess,
319  const FetchDatasetTimeoutCallback& onFetchFailure)
320 {
321  NLSR_LOG_TRACE("Initializing Faces...");
322 
323  m_faceDatasetController.fetch<ndn::nfd::FaceDataset>(onFetchSuccess, onFetchFailure);
324 
325 }
326 
327 void
328 Nlsr::processFaceDataset(const std::vector<ndn::nfd::FaceStatus>& faces)
329 {
330  NLSR_LOG_DEBUG("Processing face dataset");
331 
332  // Iterate over each neighbor listed in nlsr.conf
333  for (auto&& adjacent : m_adjacencyList.getAdjList()) {
334 
335  const std::string& faceUriString = adjacent.getFaceUri().toString();
336  // Check the list of FaceStatus objects we got for a match
337  for (const auto& faceStatus : faces) {
338  // Set the adjacency FaceID if we find a URI match and it was
339  // previously unset. Change the boolean to true.
340  if (adjacent.getFaceId() == 0 && faceUriString == faceStatus.getRemoteUri()) {
341  NLSR_LOG_DEBUG("FaceUri: " << faceStatus.getRemoteUri() <<
342  " FaceId: "<< faceStatus.getFaceId());
343  adjacent.setFaceId(faceStatus.getFaceId());
344  // Register the prefixes for each neighbor
345  this->registerAdjacencyPrefixes(adjacent, ndn::time::milliseconds::max());
346  }
347  }
348  // If this adjacency has no information in this dataset, then one
349  // of two things is happening: 1. NFD is starting slowly and this
350  // Face wasn't ready yet, or 2. NFD is configured
351  // incorrectly and this Face isn't available.
352  if (adjacent.getFaceId() == 0) {
353  NLSR_LOG_WARN("The adjacency " << adjacent.getName() <<
354  " has no Face information in this dataset.");
355  }
356  }
357 
358  scheduleDatasetFetch();
359 }
360 
361 void
362 Nlsr::registerAdjacencyPrefixes(const Adjacent& adj,
363  const ndn::time::milliseconds& timeout)
364 {
365  ndn::FaceUri faceUri = adj.getFaceUri();
366  double linkCost = adj.getLinkCost();
367  const ndn::Name& adjName = adj.getName();
368 
369  m_fib.registerPrefix(adjName, faceUri, linkCost,
370  timeout, ndn::nfd::ROUTE_FLAG_CAPTURE, 0);
371 
372  m_fib.registerPrefix(m_confParam.getLsaPrefix(),
373  faceUri, linkCost, timeout,
374  ndn::nfd::ROUTE_FLAG_CAPTURE, 0);
375 }
376 
377 void
378 Nlsr::onFaceDatasetFetchTimeout(uint32_t code,
379  const std::string& msg,
380  uint32_t nRetriesSoFar)
381 {
382  NLSR_LOG_DEBUG("onFaceDatasetFetchTimeout");
383  // If we have exceeded the maximum attempt count, do not try again.
384  if (nRetriesSoFar++ < m_confParam.getFaceDatasetFetchTries()) {
385  NLSR_LOG_DEBUG("Failed to fetch dataset: " << msg << ". Attempting retry #" << nRetriesSoFar);
386  m_faceDatasetController.fetch<ndn::nfd::FaceDataset>(std::bind(&Nlsr::processFaceDataset,
387  this, _1),
388  std::bind(&Nlsr::onFaceDatasetFetchTimeout,
389  this, _1, _2, nRetriesSoFar));
390  }
391  else {
392  NLSR_LOG_ERROR("Failed to fetch dataset: " << msg << ". Exceeded limit of " <<
393  m_confParam.getFaceDatasetFetchTries() << ", so not trying again this time.");
394  // If we fail to fetch it, just do nothing until the next
395  // interval. Since this is a backup mechanism, we aren't as
396  // concerned with retrying.
397  scheduleDatasetFetch();
398  }
399 }
400 
401 void
402 Nlsr::scheduleDatasetFetch()
403 {
404  NLSR_LOG_DEBUG("Scheduling Dataset Fetch in " << m_confParam.getFaceDatasetFetchInterval());
405 
406  m_scheduler.schedule(m_confParam.getFaceDatasetFetchInterval(),
407  [this] {
408  this->initializeFaces(
409  [this] (const std::vector<ndn::nfd::FaceStatus>& faces) {
410  this->processFaceDataset(faces);
411  },
412  [this] (uint32_t code, const std::string& msg) {
413  this->onFaceDatasetFetchTimeout(code, msg, 0);
414  });
415  });
416 }
417 
418 void
419 Nlsr::enableIncomingFaceIdIndication()
420 {
421  NLSR_LOG_DEBUG("Enabling incoming face id indication for local face.");
422 
423  m_controller.start<ndn::nfd::FaceUpdateCommand>(
424  ndn::nfd::ControlParameters()
425  .setFlagBit(ndn::nfd::FaceFlagBit::BIT_LOCAL_FIELDS_ENABLED, true),
426  std::bind(&Nlsr::onFaceIdIndicationSuccess, this, _1),
427  std::bind(&Nlsr::onFaceIdIndicationFailure, this, _1));
428 }
429 
430 void
431 Nlsr::onFaceIdIndicationSuccess(const ndn::nfd::ControlParameters& cp)
432 {
433  NLSR_LOG_DEBUG("Successfully enabled incoming face id indication"
434  << "for face id " << cp.getFaceId());
435 }
436 
437 void
438 Nlsr::onFaceIdIndicationFailure(const ndn::nfd::ControlResponse& cr)
439 {
440  NLSR_LOG_DEBUG("Failed to enable incoming face id indication feature: " <<
441  "(code: " << cr.getCode() << ", reason: " << cr.getText() << ")");
442 }
443 
444 } // namespace nlsr
A neighbor reachable over a Face.
Definition: adjacent.hpp:47
const ndn::FaceUri & getFaceUri() const
Definition: adjacent.hpp:85
const ndn::Name & getName() const
Definition: adjacent.hpp:72
double getLinkCost() const
Definition: adjacent.hpp:98
A class to house all the configuration parameters for NLSR.
Nlsr(ndn::Face &face, ndn::KeyChain &keyChain, ConfParameter &confParam)
Definition: nlsr.cpp:38
static const ndn::Name LOCALHOST_PREFIX
Definition: nlsr.hpp:192
std::function< void(const std::vector< ndn::nfd::FaceStatus > &)> FetchDatasetCallback
Definition: nlsr.hpp:62
void registerStrategyForCerts(const ndn::Name &originRouter)
Definition: nlsr.cpp:113
std::function< void(uint32_t, const std::string &)> FetchDatasetTimeoutCallback
Definition: nlsr.hpp:63
Copyright (c) 2014-2018, The University of Memphis, Regents of the University of California.
#define NLSR_LOG_DEBUG(x)
Definition: logger.hpp:38
#define INIT_LOGGER(name)
Definition: logger.hpp:35
#define NLSR_LOG_WARN(x)
Definition: logger.hpp:40
#define NLSR_LOG_ERROR(x)
Definition: logger.hpp:41
#define NLSR_LOG_TRACE(x)
Definition: logger.hpp:37
Definition: tlv-nlsr.hpp:25
Copyright (c) 2014-2020, The University of Memphis, Regents of the University of California,...
@ HYPERBOLIC_STATE_ON
@ HYPERBOLIC_STATE_OFF