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