All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros
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-2025, 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/mgmt/nfd/control-command.hpp>
31 #include <ndn-cxx/mgmt/nfd/status-dataset.hpp>
32 #include <ndn-cxx/net/face-uri.hpp>
33 
34 namespace nlsr {
35 
36 INIT_LOGGER(Nlsr);
37 
38 Nlsr::Nlsr(ndn::Face& face, ndn::KeyChain& keyChain, ConfParameter& confParam)
39  : m_face(face)
40  , m_scheduler(face.getIoContext())
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_lsdb(m_face, keyChain, m_confParam)
46  , m_routingTable(m_scheduler, m_lsdb, m_confParam)
47  , m_namePrefixTable(confParam.getRouterPrefix(), m_fib, m_routingTable,
48  m_routingTable.afterRoutingChange, m_lsdb.onLsdbModified)
49  , m_helloProtocol(m_face, keyChain, confParam, m_routingTable, m_lsdb)
50  , m_onNewLsaConnection(m_lsdb.getSync().onNewLsa.connect(
51  [this] (const ndn::Name& updateName, uint64_t sequenceNumber,
52  const ndn::Name& originRouter, uint64_t incomingFaceId) {
53  registerStrategyForCerts(originRouter);
54  }))
55  , m_onPrefixRegistrationSuccess(m_fib.onPrefixRegistrationSuccess.connect(
56  [this] (const ndn::Name& name) {
57  m_helloProtocol.sendHelloInterest(name);
58  }))
59  , m_onInitialHelloDataValidated(m_helloProtocol.onInitialHelloDataValidated.connect(
60  [this] (const ndn::Name& neighbor) {
61  auto it = m_adjacencyList.findAdjacent(neighbor);
62  if (it != m_adjacencyList.end()) {
63  m_fib.registerPrefix(m_confParam.getSyncPrefix(), it->getFaceUri(), it->getLinkCost(),
64  ndn::time::milliseconds::max(), ndn::nfd::ROUTE_FLAG_CAPTURE, 0);
65  }
66  }))
67  , m_dispatcher(m_face, keyChain)
68  , m_datasetHandler(m_dispatcher, m_lsdb, m_routingTable)
69  , m_controller(m_face, keyChain)
70  , m_faceDatasetController(m_face, keyChain)
71  , m_prefixUpdateProcessor(m_dispatcher,
72  m_confParam.getPrefixUpdateValidator(),
73  m_namePrefixList,
74  m_lsdb,
75  m_confParam.getConfFileNameDynamic())
76  , m_nfdRibCommandProcessor(m_dispatcher,
77  m_namePrefixList,
78  m_lsdb)
79  , m_statsCollector(m_lsdb, m_helloProtocol)
80  , m_faceMonitor(m_face)
81  , m_terminateSignals(face.getIoContext(), SIGINT, SIGTERM)
82 {
83  NLSR_LOG_DEBUG("Initializing Nlsr");
84 
85  m_faceMonitor.onNotification.connect(std::bind(&Nlsr::onFaceEventNotification, this, _1));
86  m_faceMonitor.start();
87 
88  m_fib.setStrategy(m_confParam.getLsaPrefix(), Fib::MULTICAST_STRATEGY, 0);
89  m_fib.setStrategy(m_confParam.getSyncPrefix(), Fib::MULTICAST_STRATEGY, 0);
90 
91  NLSR_LOG_DEBUG("Default NLSR identity: " << m_confParam.getSigningInfo().getSignerName());
92 
93  // Add top-level prefixes: router and localhost prefix
94  addDispatcherTopPrefix(ndn::Name(m_confParam.getRouterPrefix()).append("nlsr"));
95  addDispatcherTopPrefix(LOCALHOST_PREFIX);
96 
97  enableIncomingFaceIdIndication();
98 
99  initializeFaces(std::bind(&Nlsr::processFaceDataset, this, _1),
100  std::bind(&Nlsr::onFaceDatasetFetchTimeout, this, _1, _2, 0));
101 
102  m_adjacencyList.writeLog();
103  NLSR_LOG_DEBUG(m_namePrefixList);
104 
105  // Need to set direct neighbors' costs to 0 for hyperbolic routing
106  if (m_confParam.getHyperbolicState() == HYPERBOLIC_STATE_ON) {
107  for (auto&& neighbor : m_adjacencyList.getAdjList()) {
108  neighbor.setLinkCost(0);
109  }
110  }
111 
112  m_terminateSignals.async_wait([this] (auto&&... args) {
113  terminate(std::forward<decltype(args)>(args)...);
114  });
115 }
116 
117 void
118 Nlsr::registerStrategyForCerts(const ndn::Name& originRouter)
119 {
120  for (const ndn::Name& router : m_strategySetOnRouters) {
121  if (router == originRouter) {
122  // Have already set strategy for this router's certs once
123  return;
124  }
125  }
126 
127  m_strategySetOnRouters.push_back(originRouter);
128 
129  ndn::Name routerKey(originRouter);
130  routerKey.append(ndn::security::Certificate::KEY_COMPONENT);
131  ndn::Name instanceKey(originRouter);
132  instanceKey.append("nlsr").append(ndn::security::Certificate::KEY_COMPONENT);
133 
134  m_fib.setStrategy(routerKey, Fib::BEST_ROUTE_STRATEGY, 0);
135  m_fib.setStrategy(instanceKey, Fib::BEST_ROUTE_STRATEGY, 0);
136 
137  ndn::Name siteKey;
138  for (size_t i = 0; i < originRouter.size(); ++i) {
139  if (originRouter[i].toUri() == "%C1.Router") {
140  break;
141  }
142  siteKey.append(originRouter[i]);
143  }
144  ndn::Name opPrefix(siteKey);
145  siteKey.append(ndn::security::Certificate::KEY_COMPONENT);
146  m_fib.setStrategy(siteKey, Fib::BEST_ROUTE_STRATEGY, 0);
147 
148  opPrefix.append(std::string("%C1.Operator"));
149  m_fib.setStrategy(opPrefix, Fib::BEST_ROUTE_STRATEGY, 0);
150 }
151 
152 void
153 Nlsr::addDispatcherTopPrefix(const ndn::Name& topPrefix)
154 {
155  registerPrefix(topPrefix);
156  try {
157  // false since we want to have control over the registration process
158  m_dispatcher.addTopPrefix(topPrefix, false, m_confParam.getSigningInfo());
159  }
160  catch (const std::exception& e) {
161  NLSR_LOG_ERROR("Error setting top-level prefix in dispatcher: " << e.what());
162  }
163 }
164 
165 void
166 Nlsr::registerPrefix(const ndn::Name& prefix)
167 {
168  m_face.registerPrefix(prefix,
169  [] (const ndn::Name& name) {
170  NLSR_LOG_DEBUG("Successfully registered prefix " << name);
171  },
172  [] (const ndn::Name& name, const std::string& reason) {
173  NLSR_LOG_ERROR("Failed to register prefix " << name << " (" << reason << ")");
174  NDN_THROW(Error("Prefix registration failed: " + reason));
175  });
176 }
177 
178 void
179 Nlsr::onFaceEventNotification(const ndn::nfd::FaceEventNotification& faceEventNotification)
180 {
181  NLSR_LOG_TRACE("onFaceEventNotification called");
182 
183  switch (faceEventNotification.getKind()) {
184  case ndn::nfd::FACE_EVENT_DESTROYED: {
185  uint64_t faceId = faceEventNotification.getFaceId();
186 
187  auto adjacent = m_adjacencyList.findAdjacent(faceId);
188 
189  if (adjacent != m_adjacencyList.end()) {
190  NLSR_LOG_DEBUG("Face to " << adjacent->getName() << " with face id: " << faceId << " destroyed");
191 
192  adjacent->setFaceId(0);
193 
194  // Only trigger an Adjacency LSA build if this node is changing
195  // from ACTIVE to INACTIVE since this rebuild will effectively
196  // cancel the previous Adjacency LSA refresh event and schedule
197  // a new one further in the future.
198  //
199  // Continuously scheduling the refresh in the future will block
200  // the router from refreshing its Adjacency LSA. Since other
201  // routers' Name prefixes' expiration times are updated when
202  // this router refreshes its Adjacency LSA, the other routers'
203  // prefixes will expire and be removed from the RIB.
204  //
205  // This check is required to fix Bug #2733 for now. This check
206  // would be unnecessary to fix Bug #2733 when Issue #2732 is
207  // completed, but the check also helps with optimization so it
208  // can remain even when Issue #2732 is implemented.
209  if (adjacent->getStatus() == Adjacent::STATUS_ACTIVE) {
210  adjacent->setStatus(Adjacent::STATUS_INACTIVE);
211 
212  // A new adjacency LSA cannot be built until the neighbor is marked INACTIVE and
213  // has met the HELLO retry threshold
214  adjacent->setInterestTimedOutNo(m_confParam.getInterestRetryNumber());
215 
216  if (m_confParam.getHyperbolicState() == HYPERBOLIC_STATE_ON) {
217  m_routingTable.scheduleRoutingTableCalculation();
218  }
219  else {
220  // Will call scheduleRoutingTableCalculation internally
221  // if needed in case of LS or DRY_RUN
222  m_lsdb.scheduleAdjLsaBuild();
223  }
224  }
225  }
226  break;
227  }
228  case ndn::nfd::FACE_EVENT_CREATED: {
229  // Find the neighbor in our adjacency list
230  ndn::FaceUri faceUri;
231  try {
232  faceUri = ndn::FaceUri(faceEventNotification.getRemoteUri());
233  }
234  catch (const std::exception& e) {
235  NLSR_LOG_WARN(e.what());
236  return;
237  }
238  auto adjacent = m_adjacencyList.findAdjacent(faceUri);
239  uint64_t faceId = faceEventNotification.getFaceId();
240 
241  // If we have a neighbor by that FaceUri and it has no FaceId or
242  // the FaceId is different from ours, we have a match.
243  if (adjacent != m_adjacencyList.end() &&
244  (adjacent->getFaceId() == 0 || adjacent->getFaceId() != faceId))
245  {
246  NLSR_LOG_DEBUG("Face creation event matches neighbor: " << adjacent->getName()
247  << ". New Face ID: " << faceId << ". Registering prefixes.");
248  adjacent->setFaceId(faceId);
249 
250  registerAdjacencyPrefixes(*adjacent, ndn::time::milliseconds::max());
251 
252  // We should not do scheduleRoutingTableCalculation or scheduleAdjLsaBuild here
253  // because once the prefixes are registered, we send a HelloInterest
254  // to the prefix (see NLSR ctor). HelloProtocol will call these functions
255  // once HelloData is received and validated.
256  }
257  break;
258  }
259  default:
260  break;
261  }
262 }
263 
264 void
265 Nlsr::initializeFaces(const FetchDatasetCallback& onFetchSuccess,
266  const FetchDatasetTimeoutCallback& onFetchFailure)
267 {
268  NLSR_LOG_TRACE("Initializing faces");
269  m_faceDatasetController.fetch<ndn::nfd::FaceDataset>(onFetchSuccess, onFetchFailure);
270 }
271 
272 void
273 Nlsr::processFaceDataset(const std::vector<ndn::nfd::FaceStatus>& faces)
274 {
275  NLSR_LOG_DEBUG("Processing face dataset");
276 
277  // Iterate over each neighbor listed in nlsr.conf
278  for (auto&& adjacent : m_adjacencyList.getAdjList()) {
279 
280  const std::string& faceUriString = adjacent.getFaceUri().toString();
281  // Check the list of FaceStatus objects we got for a match
282  for (const auto& faceStatus : faces) {
283  // Set the adjacency FaceID if we find a URI match and it was
284  // previously unset. Change the boolean to true.
285  if (adjacent.getFaceId() == 0 && faceUriString == faceStatus.getRemoteUri()) {
286  NLSR_LOG_DEBUG("FaceUri: " << faceStatus.getRemoteUri() <<
287  " FaceId: "<< faceStatus.getFaceId());
288  adjacent.setFaceId(faceStatus.getFaceId());
289  // Register the prefixes for each neighbor
290  this->registerAdjacencyPrefixes(adjacent, ndn::time::milliseconds::max());
291  }
292  }
293  // If this adjacency has no information in this dataset, then one
294  // of two things is happening: 1. NFD is starting slowly and this
295  // Face wasn't ready yet, or 2. NFD is configured
296  // incorrectly and this Face isn't available.
297  if (adjacent.getFaceId() == 0) {
298  NLSR_LOG_WARN("The adjacency " << adjacent.getName() <<
299  " has no Face information in this dataset.");
300  }
301  }
302 
303  scheduleDatasetFetch();
304 }
305 
306 void
307 Nlsr::registerAdjacencyPrefixes(const Adjacent& adj, ndn::time::milliseconds timeout)
308 {
309  ndn::FaceUri faceUri = adj.getFaceUri();
310  double linkCost = adj.getLinkCost();
311  const ndn::Name& adjName = adj.getName();
312 
313  m_fib.registerPrefix(adjName, faceUri, linkCost,
314  timeout, ndn::nfd::ROUTE_FLAG_CAPTURE, 0);
315 
316  m_fib.registerPrefix(m_confParam.getLsaPrefix(),
317  faceUri, linkCost, timeout,
318  ndn::nfd::ROUTE_FLAG_CAPTURE, 0);
319 }
320 
321 void
322 Nlsr::onFaceDatasetFetchTimeout(uint32_t code,
323  const std::string& msg,
324  uint32_t nRetriesSoFar)
325 {
326  // If we have exceeded the maximum attempt count, do not try again.
327  if (nRetriesSoFar++ < m_confParam.getFaceDatasetFetchTries()) {
328  NLSR_LOG_DEBUG("Failed to fetch dataset: " << msg << ". Attempting retry #" << nRetriesSoFar);
329  m_faceDatasetController.fetch<ndn::nfd::FaceDataset>(std::bind(&Nlsr::processFaceDataset, this, _1),
330  std::bind(&Nlsr::onFaceDatasetFetchTimeout,
331  this, _1, _2, nRetriesSoFar));
332  }
333  else {
334  NLSR_LOG_ERROR("Failed to fetch dataset: " << msg << ". Exceeded limit of " <<
335  m_confParam.getFaceDatasetFetchTries() << ", so not trying again this time.");
336  // If we fail to fetch it, just do nothing until the next
337  // interval. Since this is a backup mechanism, we aren't as
338  // concerned with retrying.
339  scheduleDatasetFetch();
340  }
341 }
342 
343 void
344 Nlsr::scheduleDatasetFetch()
345 {
346  NLSR_LOG_DEBUG("Scheduling dataset fetch in " << m_confParam.getFaceDatasetFetchInterval());
347 
348  m_scheduler.schedule(m_confParam.getFaceDatasetFetchInterval(), [this] {
349  initializeFaces(
350  [this] (const auto& faces) { processFaceDataset(faces); },
351  [this] (uint32_t code, const std::string& msg) { onFaceDatasetFetchTimeout(code, msg, 0); });
352  });
353 }
354 
355 void
356 Nlsr::enableIncomingFaceIdIndication()
357 {
358  NLSR_LOG_DEBUG("Enabling incoming face id indication for local face.");
359 
360  m_controller.start<ndn::nfd::FaceUpdateCommand>(
361  ndn::nfd::ControlParameters()
362  .setFlagBit(ndn::nfd::FaceFlagBit::BIT_LOCAL_FIELDS_ENABLED, true),
363  [] (const ndn::nfd::ControlParameters& cp) {
364  NLSR_LOG_DEBUG("Successfully enabled incoming face id indication"
365  << "for face id " << cp.getFaceId());
366  },
367  [] (const ndn::nfd::ControlResponse& cr) {
368  NLSR_LOG_WARN("Failed to enable incoming face id indication feature: " <<
369  "(code: " << cr.getCode() << ", reason: " << cr.getText() << ")");
370  });
371 }
372 
373 void
374 Nlsr::terminate(const boost::system::error_code& error, int signalNo)
375 {
376  if (error)
377  return;
378  NLSR_LOG_INFO("Caught signal " << signalNo << " (" << ::strsignal(signalNo) << "), exiting...");
379  m_face.getIoContext().stop();
380 }
381 
382 } // namespace nlsr
A class to house all the configuration parameters for NLSR.
Nlsr(ndn::Face &face, ndn::KeyChain &keyChain, ConfParameter &confParam)
Definition: nlsr.cpp:38
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
#define NLSR_LOG_INFO(x)
Definition: logger.hpp:39
Copyright (c) 2014-2020, The University of Memphis, Regents of the University of California.
@ HYPERBOLIC_STATE_ON