conf-file-processor.cpp
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * Copyright (c) 2014-2020, 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 "conf-file-processor.hpp"
23 #include "adjacent.hpp"
24 #include "utility/name-helper.hpp"
26 
27 #include <ndn-cxx/name.hpp>
28 #include <ndn-cxx/net/face-uri.hpp>
29 
30 #include <iostream>
31 #include <fstream>
32 
33 namespace nlsr {
34 
35 template <class T>
37 {
38 public:
39  typedef std::function<void(T)> ConfParameterCallback;
40 
41  ConfigurationVariable(const std::string& key, const ConfParameterCallback& setter)
42  : m_key(key)
43  , m_setterCallback(setter)
44  , m_minValue(0)
45  , m_maxValue(0)
46  , m_shouldCheckRange(false)
47  , m_isRequired(true)
48  {
49  }
50 
51  bool
53  {
54  try {
55  T value = section.get<T>(m_key);
56 
57  if (!isValidValue(value)) {
58  return false;
59  }
60 
61  m_setterCallback(value);
62  return true;
63  }
64  catch (const std::exception& ex) {
65 
66  if (m_isRequired) {
67  std::cerr << ex.what() << std::endl;
68  std::cerr << "Missing required configuration variable" << std::endl;
69  return false;
70  }
71  else {
72  m_setterCallback(m_defaultValue);
73  return true;
74  }
75  }
76 
77  return false;
78  }
79 
80  void
81  setMinAndMaxValue(T min, T max)
82  {
83  m_minValue = min;
84  m_maxValue = max;
85  m_shouldCheckRange = true;
86  }
87 
88  void
89  setOptional(T defaultValue)
90  {
91  m_isRequired = false;
92  m_defaultValue = defaultValue;
93  }
94 
95 private:
96  void
97  printOutOfRangeError(T value)
98  {
99  std::cerr << "Invalid value for " << m_key << ": "
100  << value << ". "
101  << "Valid values: "
102  << m_minValue << " - "
103  << m_maxValue << std::endl;
104  }
105 
106  bool
107  isValidValue(T value)
108  {
109  if (!m_shouldCheckRange) {
110  return true;
111  }
112  else if (value < m_minValue || value > m_maxValue)
113  {
114  printOutOfRangeError(value);
115  return false;
116  }
117 
118  return true;
119  }
120 
121 private:
122  const std::string m_key;
123  const ConfParameterCallback m_setterCallback;
124  T m_defaultValue;
125 
126  T m_minValue;
127  T m_maxValue;
128 
129  bool m_shouldCheckRange;
130  bool m_isRequired;
131 };
132 
134  : m_confFileName(confParam.getConfFileName())
135  , m_confParam(confParam)
136 {
137 }
138 
139 bool
141 {
142  bool ret = true;
143  std::ifstream inputFile;
144  inputFile.open(m_confFileName.c_str());
145  if (!inputFile.is_open()) {
146  std::string msg = "Failed to read configuration file: ";
147  msg += m_confFileName;
148  std::cerr << msg << std::endl;
149  return false;
150  }
151  ret = load(inputFile);
152  inputFile.close();
153 
154  if (ret) {
155  m_confParam.buildRouterAndSyncUserPrefix();
156  m_confParam.writeLog();
157  }
158 
159  return ret;
160 }
161 
162 bool
163 ConfFileProcessor::load(std::istream& input)
164 {
165  ConfigSection pt;
166  try {
167  boost::property_tree::read_info(input, pt);
168  }
169  catch (const boost::property_tree::info_parser_error& error) {
170  std::stringstream msg;
171  std::cerr << "Failed to parse configuration file " << std::endl;
172  std::cerr << m_confFileName << std::endl;
173  return false;
174  }
175 
176  for (const auto& tn : pt) {
177  if (!processSection(tn.first, tn.second)) {
178  return false;
179  }
180  }
181  return true;
182 }
183 
184 bool
185 ConfFileProcessor::processSection(const std::string& sectionName, const ConfigSection& section)
186 {
187  bool ret = true;
188  if (sectionName == "general")
189  {
190  ret = processConfSectionGeneral(section);
191  }
192  else if (sectionName == "neighbors")
193  {
194  ret = processConfSectionNeighbors(section);
195  }
196  else if (sectionName == "hyperbolic")
197  {
198  ret = processConfSectionHyperbolic(section);
199  }
200  else if (sectionName == "fib")
201  {
202  ret = processConfSectionFib(section);
203  }
204  else if (sectionName == "advertising")
205  {
206  ret = processConfSectionAdvertising(section);
207  }
208  else if (sectionName == "security")
209  {
210  ret = processConfSectionSecurity(section);
211  }
212  else
213  {
214  std::cerr << "Wrong configuration section: " << sectionName << std::endl;
215  }
216  return ret;
217 }
218 
219 bool
220 ConfFileProcessor::processConfSectionGeneral(const ConfigSection& section)
221 {
222  try {
223  std::string network = section.get<std::string>("network");
224  std::string site = section.get<std::string>("site");
225  std::string router = section.get<std::string>("router");
226  ndn::Name networkName(network);
227  if (!networkName.empty()) {
228  m_confParam.setNetwork(networkName);
229  }
230  else {
231  std::cerr << " Network can not be null or empty or in bad URI format :(!" << std::endl;
232  return false;
233  }
234  ndn::Name siteName(site);
235  if (!siteName.empty()) {
236  m_confParam.setSiteName(siteName);
237  }
238  else {
239  std::cerr << "Site can not be null or empty or in bad URI format:( !" << std::endl;
240  return false;
241  }
242  ndn::Name routerName(router);
243  if (!routerName.empty()) {
244  m_confParam.setRouterName(routerName);
245  }
246  else {
247  std::cerr << " Router name can not be null or empty or in bad URI format:( !" << std::endl;
248  return false;
249  }
250  }
251  catch (const std::exception& ex) {
252  std::cerr << ex.what() << std::endl;
253  return false;
254  }
255 
256  // lsa-refresh-time
257  uint32_t lsaRefreshTime = section.get<uint32_t>("lsa-refresh-time", LSA_REFRESH_TIME_DEFAULT);
258 
259  if (lsaRefreshTime >= LSA_REFRESH_TIME_MIN && lsaRefreshTime <= LSA_REFRESH_TIME_MAX) {
260  m_confParam.setLsaRefreshTime(lsaRefreshTime);
261  }
262  else {
263  std::cerr << "Wrong value for lsa-refresh-time ";
264  std::cerr << "Allowed value: " << LSA_REFRESH_TIME_MIN << "-";
265  std::cerr << LSA_REFRESH_TIME_MAX << std::endl;
266 
267  return false;
268  }
269 
270  // router-dead-interval
271  uint32_t routerDeadInterval = section.get<uint32_t>("router-dead-interval", (2*lsaRefreshTime));
272 
273  if (routerDeadInterval > m_confParam.getLsaRefreshTime()) {
274  m_confParam.setRouterDeadInterval(routerDeadInterval);
275  }
276  else {
277  std::cerr << "Value of router-dead-interval must be larger than lsa-refresh-time" << std::endl;
278  return false;
279  }
280 
281  // lsa-interest-lifetime
282  int lifetime = section.get<int>("lsa-interest-lifetime", LSA_INTEREST_LIFETIME_DEFAULT);
283 
284  if (lifetime >= LSA_INTEREST_LIFETIME_MIN && lifetime <= LSA_INTEREST_LIFETIME_MAX) {
285  m_confParam.setLsaInterestLifetime(ndn::time::seconds(lifetime));
286  }
287  else {
288  std::cerr << "Wrong value for lsa-interest-timeout. "
289  << "Allowed value:" << LSA_INTEREST_LIFETIME_MIN << "-"
290  << LSA_INTEREST_LIFETIME_MAX << std::endl;
291 
292  return false;
293  }
294 
295  // sync-protocol
296  std::string syncProtocol = section.get<std::string>("sync-protocol", "chronosync");
297  if (syncProtocol == "chronosync") {
299  }
300  else if (syncProtocol == "psync") {
302  }
303  else {
304  std::cerr << "Sync protocol " << syncProtocol << " is not supported!"
305  << "Use chronosync or psync" << std::endl;
306  return false;
307  }
308 
309  // sync-interest-lifetime
310  uint32_t syncInterestLifetime = section.get<uint32_t>("sync-interest-lifetime",
312  if (syncInterestLifetime >= SYNC_INTEREST_LIFETIME_MIN &&
313  syncInterestLifetime <= SYNC_INTEREST_LIFETIME_MAX) {
314  m_confParam.setSyncInterestLifetime(syncInterestLifetime);
315  }
316  else {
317  std::cerr << "Wrong value for sync-interest-lifetime. "
318  << "Allowed value:" << SYNC_INTEREST_LIFETIME_MIN << "-"
319  << SYNC_INTEREST_LIFETIME_MAX << std::endl;
320 
321  return false;
322  }
323 
324  try {
325  std::string stateDir = section.get<std::string>("state-dir");
326  if (bf::exists(stateDir)) {
327  if (bf::is_directory(stateDir)) {
328 
329  // copying nlsr.conf file to a user define directory for possible modification
330  std::string conFileDynamic = (bf::path(stateDir) / "nlsr.conf").c_str();
331 
332  if (m_confFileName == conFileDynamic) {
333  std::cerr << "Please use nlsr.conf stored at another location "
334  << "or change the state-dir in the configuration." << std::endl;
335  std::cerr << "The file at " << conFileDynamic <<
336  " is used as dynamic file for saving NLSR runtime changes." << std::endl;
337  std::cerr << "The dynamic file can be used for next run "
338  << "after copying to another location." << std::endl;
339  return false;
340  }
341 
342  m_confParam.setConfFileNameDynamic(conFileDynamic);
343  try {
344  bf::copy_file(m_confFileName, conFileDynamic, bf::copy_option::overwrite_if_exists);
345  }
346  catch (const bf::filesystem_error& e) {
347  std::cerr << "Error copying conf file to the state directory: " << e.what() << std::endl;
348  }
349 
350  std::string testFileName = (bf::path(stateDir) / "test.seq").c_str();
351  std::ofstream testOutFile(testFileName);
352  if (testOutFile) {
353  m_confParam.setStateFileDir(stateDir);
354  }
355  else {
356  std::cerr << "User does not have read and write permission on the state directory";
357  std::cerr << std::endl;
358  return false;
359  }
360  testOutFile.close();
361  remove(testFileName.c_str());
362  }
363  else {
364  std::cerr << "Provided: " << stateDir << "is not a directory" << std::endl;
365  return false;
366  }
367  }
368  else {
369  std::cerr << "Provided state directory <" << stateDir << "> does not exist" << std::endl;
370  return false;
371  }
372  }
373  catch (const std::exception& ex) {
374  std::cerr << "You must configure state directory" << std::endl;
375  std::cerr << ex.what() << std::endl;
376  return false;
377  }
378 
379  return true;
380 }
381 
382 bool
383 ConfFileProcessor::processConfSectionNeighbors(const ConfigSection& section)
384 {
385  // hello-retries
386  int retrials = section.get<int>("hello-retries", HELLO_RETRIES_DEFAULT);
387 
388  if (retrials >= HELLO_RETRIES_MIN && retrials <= HELLO_RETRIES_MAX) {
389  m_confParam.setInterestRetryNumber(retrials);
390  }
391  else {
392  std::cerr << "Wrong value for hello-retries." << std::endl;
393  std::cerr << "Allowed value:" << HELLO_RETRIES_MIN << "-";
394  std::cerr << HELLO_RETRIES_MAX << std::endl;
395 
396  return false;
397  }
398 
399  // hello-timeout
400  uint32_t timeOut = section.get<uint32_t>("hello-timeout", HELLO_TIMEOUT_DEFAULT);
401 
402  if (timeOut >= HELLO_TIMEOUT_MIN && timeOut <= HELLO_TIMEOUT_MAX) {
403  m_confParam.setInterestResendTime(timeOut);
404  }
405  else {
406  std::cerr << "Wrong value for hello-timeout. ";
407  std::cerr << "Allowed value:" << HELLO_TIMEOUT_MIN << "-";
408  std::cerr << HELLO_TIMEOUT_MAX << std::endl;
409 
410  return false;
411  }
412 
413  // hello-interval
414  uint32_t interval = section.get<uint32_t>("hello-interval", HELLO_INTERVAL_DEFAULT);
415 
416  if (interval >= HELLO_INTERVAL_MIN && interval <= HELLO_INTERVAL_MAX) {
417  m_confParam.setInfoInterestInterval(interval);
418  }
419  else {
420  std::cerr << "Wrong value for hello-interval. ";
421  std::cerr << "Allowed value:" << HELLO_INTERVAL_MIN << "-";
422  std::cerr << HELLO_INTERVAL_MAX << std::endl;
423 
424  return false;
425  }
426 
427  // Event intervals
428  // adj-lsa-build-interval
429  ConfigurationVariable<uint32_t> adjLsaBuildInterval("adj-lsa-build-interval",
431  &m_confParam, _1));
433  adjLsaBuildInterval.setOptional(ADJ_LSA_BUILD_INTERVAL_DEFAULT);
434 
435  if (!adjLsaBuildInterval.parseFromConfigSection(section)) {
436  return false;
437  }
438  // Set the retry count for fetching the FaceStatus dataset
439  ConfigurationVariable<uint32_t> faceDatasetFetchTries("face-dataset-fetch-tries",
441  &m_confParam,
442  _1));
443 
444  faceDatasetFetchTries.setMinAndMaxValue(FACE_DATASET_FETCH_TRIES_MIN,
446  faceDatasetFetchTries.setOptional(FACE_DATASET_FETCH_TRIES_DEFAULT);
447 
448  if (!faceDatasetFetchTries.parseFromConfigSection(section)) {
449  return false;
450  }
451 
452  // Set the interval between FaceStatus dataset fetch attempts.
453  ConfigurationVariable<uint32_t> faceDatasetFetchInterval("face-dataset-fetch-interval",
455  &m_confParam,
456  _1));
457 
458  faceDatasetFetchInterval.setMinAndMaxValue(FACE_DATASET_FETCH_INTERVAL_MIN,
460  faceDatasetFetchInterval.setOptional(FACE_DATASET_FETCH_INTERVAL_DEFAULT);
461 
462  if (!faceDatasetFetchInterval.parseFromConfigSection(section)) {
463  return false;
464  }
465 
466  for (const auto& tn : section) {
467  if (tn.first == "neighbor") {
468  try {
469  ConfigSection CommandAttriTree = tn.second;
470  std::string name = CommandAttriTree.get<std::string>("name");
471  std::string uriString = CommandAttriTree.get<std::string>("face-uri");
472 
473  ndn::FaceUri faceUri;
474  if (!faceUri.parse(uriString)) {
475  std::cerr << "face-uri parsing failed" << std::endl;
476  return false;
477  }
478 
479  bool failedToCanonize = false;
480  faceUri.canonize([&faceUri] (const auto& canonicalUri) {
481  faceUri = canonicalUri;
482  },
483  [&faceUri, &failedToCanonize] (const auto& reason) {
484  failedToCanonize = true;
485  std::cerr << "Could not canonize URI: '" << faceUri
486  << "' because: " << reason << std::endl;
487  },
488  m_io,
490  m_io.run();
491  m_io.reset();
492 
493  if (failedToCanonize) {
494  return false;
495  }
496 
497  double linkCost = CommandAttriTree.get<double>("link-cost", Adjacent::DEFAULT_LINK_COST);
498  ndn::Name neighborName(name);
499  if (!neighborName.empty()) {
500  Adjacent adj(name, faceUri, linkCost, Adjacent::STATUS_INACTIVE, 0, 0);
501  m_confParam.getAdjacencyList().insert(adj);
502  }
503  else {
504  std::cerr << " Wrong command format ! [name /nbr/name/ \n face-uri /uri\n]";
505  std::cerr << " or bad URI format" << std::endl;
506  }
507  }
508  catch (const std::exception& ex) {
509  std::cerr << ex.what() << std::endl;
510  return false;
511  }
512  }
513  }
514  return true;
515 }
516 
517 bool
518 ConfFileProcessor::processConfSectionHyperbolic(const ConfigSection& section)
519 {
520  // state
521  std::string state = section.get<std::string>("state", "off");
522 
523  if (boost::iequals(state, "off")) {
525  }
526  else if (boost::iequals(state, "on")) {
528  }
529  else if (state == "dry-run") {
531  }
532  else {
533  std::cerr << "Wrong format for hyperbolic state." << std::endl;
534  std::cerr << "Allowed value: off, on, dry-run" << std::endl;
535 
536  return false;
537  }
538 
539  try {
540  // Radius and angle(s) are mandatory configuration parameters in hyperbolic section.
541  // Even if router can have hyperbolic routing calculation off but other router
542  // in the network may use hyperbolic routing calculation for FIB generation.
543  // So each router need to advertise its hyperbolic coordinates in the network
544  double radius = section.get<double>("radius");
545  std::string angleString = section.get<std::string>("angle");
546 
547  std::stringstream ss(angleString);
548  std::vector<double> angles;
549 
550  double angle;
551 
552  while (ss >> angle) {
553  angles.push_back(angle);
554  if (ss.peek() == ',' || ss.peek() == ' ') {
555  ss.ignore();
556  }
557  }
558 
559  if (!m_confParam.setCorR(radius)) {
560  return false;
561  }
562  m_confParam.setCorTheta(angles);
563  }
564  catch (const std::exception& ex) {
565  std::cerr << ex.what() << std::endl;
566  if (state == "on" || state == "dry-run") {
567  return false;
568  }
569  }
570 
571  return true;
572 }
573 
574 bool
575 ConfFileProcessor::processConfSectionFib(const ConfigSection& section)
576 {
577  // max-faces-per-prefix
578  int maxFacesPerPrefix = section.get<int>("max-faces-per-prefix", MAX_FACES_PER_PREFIX_DEFAULT);
579 
580  if (maxFacesPerPrefix >= MAX_FACES_PER_PREFIX_MIN &&
581  maxFacesPerPrefix <= MAX_FACES_PER_PREFIX_MAX)
582  {
583  m_confParam.setMaxFacesPerPrefix(maxFacesPerPrefix);
584  }
585  else {
586  std::cerr << "Wrong value for max-faces-per-prefix. ";
587  std::cerr << MAX_FACES_PER_PREFIX_MIN << std::endl;
588 
589  return false;
590  }
591 
592  // routing-calc-interval
593  ConfigurationVariable<uint32_t> routingCalcInterval("routing-calc-interval",
595  &m_confParam, _1));
597  routingCalcInterval.setOptional(ROUTING_CALC_INTERVAL_DEFAULT);
598 
599  if (!routingCalcInterval.parseFromConfigSection(section)) {
600  return false;
601  }
602 
603  return true;
604 }
605 
606 bool
607 ConfFileProcessor::processConfSectionAdvertising(const ConfigSection& section)
608 {
609  for (const auto& tn : section) {
610  if (tn.first == "prefix") {
611  try {
612  ndn::Name namePrefix(tn.second.data());
613  if (!namePrefix.empty()) {
614  m_confParam.getNamePrefixList().insert(namePrefix);
615  }
616  else {
617  std::cerr << " Wrong command format ! [prefix /name/prefix] or bad URI" << std::endl;
618  return false;
619  }
620  }
621  catch (const std::exception& ex) {
622  std::cerr << ex.what() << std::endl;
623  return false;
624  }
625  }
626  }
627  return true;
628 }
629 
630 bool
631 ConfFileProcessor::processConfSectionSecurity(const ConfigSection& section)
632 {
633  ConfigSection::const_iterator it = section.begin();
634 
635  if (it == section.end() || it->first != "validator") {
636  std::cerr << "Error: Expect validator section!" << std::endl;
637  return false;
638  }
639 
640  m_confParam.getValidator().load(it->second, m_confFileName);
641 
642  it++;
643  if (it != section.end() && it->first == "prefix-update-validator") {
644  m_confParam.getPrefixUpdateValidator().load(it->second, m_confFileName);
645 
646  it++;
647  for (; it != section.end(); it++) {
648 
649  if (it->first != "cert-to-publish") {
650  std::cerr << "Error: Expect cert-to-publish!" << std::endl;
651  return false;
652  }
653 
654  std::string file = it->second.data();
655  bf::path certfilePath = absolute(file, bf::path(m_confFileName).parent_path());
656  auto idCert = ndn::io::load<ndn::security::Certificate>(certfilePath.string());
657 
658  if (idCert == nullptr) {
659  std::cerr << "Error: Cannot load cert-to-publish: " << file << "!" << std::endl;
660  return false;
661  }
662  m_confParam.addCertPath(certfilePath.string());
663  m_confParam.loadCertToValidator(*idCert);
664  }
665  }
666 
667  return true;
668 }
669 
670 } // namespace nlsr
ndn::security::ValidatorConfig & getValidator()
A class to house all the configuration parameters for NLSR.
uint32_t getLsaRefreshTime() const
void setLsaInterestLifetime(const ndn::time::seconds &lifetime)
void setStateFileDir(const std::string &ssfd)
void setMaxFacesPerPrefix(uint32_t mfpp)
static const double DEFAULT_LINK_COST
Definition: adjacent.hpp:190
void setRoutingCalcInterval(uint32_t interval)
void setNetwork(const ndn::Name &networkName)
AdjacencyList & getAdjacencyList()
void setAdjLsaBuildInterval(uint32_t interval)
void setSiteName(const ndn::Name &siteName)
ndn::security::ValidatorConfig & getPrefixUpdateValidator()
void setInterestResendTime(uint32_t irt)
void setInfoInterestInterval(uint32_t iii)
bool insert(const ndn::Name &name, const std::string &source="")
inserts name into NamePrefixList
void setCorTheta(const std::vector< double > &ct)
void setSyncInterestLifetime(uint32_t syncInterestLifetime)
ConfigurationVariable(const std::string &key, const ConfParameterCallback &setter)
void setSyncProtocol(int32_t syncProtocol)
void setRouterName(const ndn::Name &routerName)
void setFaceDatasetFetchInterval(uint32_t interval)
void setInterestRetryNumber(uint32_t irn)
void setMinAndMaxValue(T min, T max)
A neighbor reachable over a Face.
Definition: adjacent.hpp:46
void addCertPath(const std::string &certPath)
bool setCorR(double cr)
void setOptional(T defaultValue)
Copyright (c) 2014-2020, The University of Memphis, Regents of the University of California, Arizona Board of Regents.
void setConfFileNameDynamic(const std::string &confFileDynamic)
void setRouterDeadInterval(uint32_t rdt)
NamePrefixList & getNamePrefixList()
const ndn::time::seconds TIME_ALLOWED_FOR_CANONIZATION
Definition: common.hpp:40
void setLsaRefreshTime(uint32_t lrt)
boost::property_tree::ptree ConfigSection
ConfFileProcessor(ConfParameter &confParam)
void setHyperbolicState(int32_t ihc)
void setFaceDatasetFetchTries(uint32_t count)
bool insert(Adjacent &adjacent)
std::function< void(T)> ConfParameterCallback
bool parseFromConfigSection(const ConfigSection &section)
void loadCertToValidator(const ndn::security::Certificate &cert)
bool processConfFile()
Load and parse the configuration file, then populate NLSR.
void writeLog()
Dump the current state of all attributes to the log.