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  typedef boost::property_tree::ptree ConfigSection;
43 
44  ConfigurationVariable(const std::string& key, const ConfParameterCallback& setter)
45  : m_key(key)
46  , m_setterCallback(setter)
47  , m_minValue(0)
48  , m_maxValue(0)
49  , m_shouldCheckRange(false)
50  , m_isRequired(true)
51  {
52  }
53 
54  bool
55  parseFromConfigSection(const ConfigSection& section)
56  {
57  try {
58  T value = section.get<T>(m_key);
59 
60  if (!isValidValue(value)) {
61  return false;
62  }
63 
64  m_setterCallback(value);
65  return true;
66  }
67  catch (const std::exception& ex) {
68 
69  if (m_isRequired) {
70  std::cerr << ex.what() << std::endl;
71  std::cerr << "Missing required configuration variable" << std::endl;
72  return false;
73  }
74  else {
75  m_setterCallback(m_defaultValue);
76  return true;
77  }
78  }
79 
80  return false;
81  }
82 
83  void
84  setMinAndMaxValue(T min, T max)
85  {
86  m_minValue = min;
87  m_maxValue = max;
88  m_shouldCheckRange = true;
89  }
90 
91  void
92  setOptional(T defaultValue)
93  {
94  m_isRequired = false;
95  m_defaultValue = defaultValue;
96  }
97 
98 private:
99  void
100  printOutOfRangeError(T value)
101  {
102  std::cerr << "Invalid value for " << m_key << ": "
103  << value << ". "
104  << "Valid values: "
105  << m_minValue << " - "
106  << m_maxValue << std::endl;
107  }
108 
109  bool
110  isValidValue(T value)
111  {
112  if (!m_shouldCheckRange) {
113  return true;
114  }
115  else if (value < m_minValue || value > m_maxValue)
116  {
117  printOutOfRangeError(value);
118  return false;
119  }
120 
121  return true;
122  }
123 
124 private:
125  const std::string m_key;
126  const ConfParameterCallback m_setterCallback;
127  T m_defaultValue;
128 
129  T m_minValue;
130  T m_maxValue;
131 
132  bool m_shouldCheckRange;
133  bool m_isRequired;
134 };
135 
137  : m_confFileName(confParam.getConfFileName())
138  , m_confParam(confParam)
139 {
140 }
141 
142 bool
144 {
145  bool ret = true;
146  std::ifstream inputFile;
147  inputFile.open(m_confFileName.c_str());
148  if (!inputFile.is_open()) {
149  std::string msg = "Failed to read configuration file: ";
150  msg += m_confFileName;
151  std::cerr << msg << std::endl;
152  return false;
153  }
154  ret = load(inputFile);
155  inputFile.close();
156  return ret;
157 }
158 
159 bool
160 ConfFileProcessor::load(std::istream& input)
161 {
162  ConfigSection pt;
163  bool ret = true;
164  try {
165  boost::property_tree::read_info(input, pt);
166  }
167  catch (const boost::property_tree::info_parser_error& error) {
168  std::stringstream msg;
169  std::cerr << "Failed to parse configuration file " << std::endl;
170  std::cerr << m_confFileName << std::endl;
171  return false;
172  }
173 
174  for (ConfigSection::const_iterator tn = pt.begin();
175  tn != pt.end(); ++tn) {
176  ret = processSection(tn->first, tn->second);
177  if (ret == false) {
178  break;
179  }
180  }
181  return ret;
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 (boost::filesystem::exists(stateDir)) {
327  if (boost::filesystem::is_directory(stateDir)) {
328 
329  // copying nlsr.conf file to a user define directory for possible modification
330  std::string conFileDynamic = (boost::filesystem::path(stateDir) / "nlsr.conf").c_str();
331  m_confParam.setConfFileNameDynamic(conFileDynamic);
332  try {
333  copy_file(m_confFileName, conFileDynamic, boost::filesystem::copy_option::overwrite_if_exists);
334  }
335  catch (const boost::filesystem::filesystem_error& e) {
336  std::cerr << "Error copying conf file to the state directory: " << e.what() << std::endl;
337  }
338  std::string testFileName = (boost::filesystem::path(stateDir) / "test.seq").c_str();
339  std::ofstream testOutFile(testFileName);
340  if (testOutFile) {
341  m_confParam.setStateFileDir(stateDir);
342  }
343  else {
344  std::cerr << "User does not have read and write permission on the state directory";
345  std::cerr << std::endl;
346  return false;
347  }
348  testOutFile.close();
349  remove(testFileName.c_str());
350  }
351  else {
352  std::cerr << "Provided: " << stateDir << "is not a directory" << std::endl;
353  return false;
354  }
355  }
356  else {
357  std::cerr << "Provided state directory <" << stateDir << "> does not exist" << std::endl;
358  return false;
359  }
360  }
361  catch (const std::exception& ex) {
362  std::cerr << "You must configure state directory" << std::endl;
363  std::cerr << ex.what() << std::endl;
364  return false;
365  }
366 
367  return true;
368 }
369 
370 bool
371 ConfFileProcessor::processConfSectionNeighbors(const ConfigSection& section)
372 {
373  // hello-retries
374  int retrials = section.get<int>("hello-retries", HELLO_RETRIES_DEFAULT);
375 
376  if (retrials >= HELLO_RETRIES_MIN && retrials <= HELLO_RETRIES_MAX) {
377  m_confParam.setInterestRetryNumber(retrials);
378  }
379  else {
380  std::cerr << "Wrong value for hello-retries." << std::endl;
381  std::cerr << "Allowed value:" << HELLO_RETRIES_MIN << "-";
382  std::cerr << HELLO_RETRIES_MAX << std::endl;
383 
384  return false;
385  }
386 
387  // hello-timeout
388  uint32_t timeOut = section.get<uint32_t>("hello-timeout", HELLO_TIMEOUT_DEFAULT);
389 
390  if (timeOut >= HELLO_TIMEOUT_MIN && timeOut <= HELLO_TIMEOUT_MAX) {
391  m_confParam.setInterestResendTime(timeOut);
392  }
393  else {
394  std::cerr << "Wrong value for hello-timeout. ";
395  std::cerr << "Allowed value:" << HELLO_TIMEOUT_MIN << "-";
396  std::cerr << HELLO_TIMEOUT_MAX << std::endl;
397 
398  return false;
399  }
400 
401  // hello-interval
402  uint32_t interval = section.get<uint32_t>("hello-interval", HELLO_INTERVAL_DEFAULT);
403 
404  if (interval >= HELLO_INTERVAL_MIN && interval <= HELLO_INTERVAL_MAX) {
405  m_confParam.setInfoInterestInterval(interval);
406  }
407  else {
408  std::cerr << "Wrong value for hello-interval. ";
409  std::cerr << "Allowed value:" << HELLO_INTERVAL_MIN << "-";
410  std::cerr << HELLO_INTERVAL_MAX << std::endl;
411 
412  return false;
413  }
414 
415  // Event intervals
416  // adj-lsa-build-interval
417  ConfigurationVariable<uint32_t> adjLsaBuildInterval("adj-lsa-build-interval",
419  &m_confParam, _1));
421  adjLsaBuildInterval.setOptional(ADJ_LSA_BUILD_INTERVAL_DEFAULT);
422 
423  if (!adjLsaBuildInterval.parseFromConfigSection(section)) {
424  return false;
425  }
426  // Set the retry count for fetching the FaceStatus dataset
427  ConfigurationVariable<uint32_t> faceDatasetFetchTries("face-dataset-fetch-tries",
429  &m_confParam,
430  _1));
431 
432  faceDatasetFetchTries.setMinAndMaxValue(FACE_DATASET_FETCH_TRIES_MIN,
434  faceDatasetFetchTries.setOptional(FACE_DATASET_FETCH_TRIES_DEFAULT);
435 
436  if (!faceDatasetFetchTries.parseFromConfigSection(section)) {
437  return false;
438  }
439 
440  // Set the interval between FaceStatus dataset fetch attempts.
441  ConfigurationVariable<uint32_t> faceDatasetFetchInterval("face-dataset-fetch-interval",
443  &m_confParam,
444  _1));
445 
446  faceDatasetFetchInterval.setMinAndMaxValue(FACE_DATASET_FETCH_INTERVAL_MIN,
448  faceDatasetFetchInterval.setOptional(FACE_DATASET_FETCH_INTERVAL_DEFAULT);
449 
450  if (!faceDatasetFetchInterval.parseFromConfigSection(section)) {
451  return false;
452  }
453 
454  // first-hello-interval
455  ConfigurationVariable<uint32_t> firstHelloInterval("first-hello-interval",
457  &m_confParam, _1));
459  firstHelloInterval.setOptional(FIRST_HELLO_INTERVAL_DEFAULT);
460 
461  if (!firstHelloInterval.parseFromConfigSection(section)) {
462  return false;
463  }
464 
465  for (ConfigSection::const_iterator tn =
466  section.begin(); tn != section.end(); ++tn) {
467 
468  if (tn->first == "neighbor") {
469  try {
470  ConfigSection CommandAttriTree = tn->second;
471  std::string name = CommandAttriTree.get<std::string>("name");
472  std::string uriString = CommandAttriTree.get<std::string>("face-uri");
473 
474  ndn::FaceUri faceUri;
475  if (! faceUri.parse(uriString)) {
476  std::cerr << "Parsing failed!" << std::endl;
477  return false;
478  }
479 
480  bool failedToCanonize = false;
481  faceUri.canonize([&faceUri] (ndn::FaceUri canonicalUri) {
482  faceUri = canonicalUri;
483  },
484  [&faceUri, &failedToCanonize] (const std::string& reason) {
485  failedToCanonize = true;
486  std::cerr << "Could not canonize URI: " << faceUri
487  << "because: " << reason << std::endl;
488  },
489  m_io,
491  m_io.run();
492 
493  if (failedToCanonize) {
494  return false;
495  }
496 
497  double linkCost = CommandAttriTree.get<double>("link-cost",
499  ndn::Name neighborName(name);
500  if (!neighborName.empty()) {
501  Adjacent adj(name, faceUri, linkCost, Adjacent::STATUS_INACTIVE, 0, 0);
502  m_confParam.getAdjacencyList().insert(adj);
503  }
504  else {
505  std::cerr << " Wrong command format ! [name /nbr/name/ \n face-uri /uri\n]";
506  std::cerr << " or bad URI format" << std::endl;
507  }
508  }
509  catch (const std::exception& ex) {
510  std::cerr << ex.what() << std::endl;
511  return false;
512  }
513  }
514  }
515  return true;
516 }
517 
518 bool
519 ConfFileProcessor::processConfSectionHyperbolic(const ConfigSection& section)
520 {
521  // state
522  std::string state = section.get<std::string>("state", "off");
523 
524  if (boost::iequals(state, "off")) {
526  }
527  else if (boost::iequals(state, "on")) {
529  }
530  else if (state == "dry-run") {
532  }
533  else {
534  std::cerr << "Wrong format for hyperbolic state." << std::endl;
535  std::cerr << "Allowed value: off, on, dry-run" << std::endl;
536 
537  return false;
538  }
539 
540  try {
541  // Radius and angle(s) are mandatory configuration parameters in hyperbolic section.
542  // Even if router can have hyperbolic routing calculation off but other router
543  // in the network may use hyperbolic routing calculation for FIB generation.
544  // So each router need to advertise its hyperbolic coordinates in the network
545  double radius = section.get<double>("radius");
546  std::string angleString = section.get<std::string>("angle");
547 
548  std::stringstream ss(angleString);
549  std::vector<double> angles;
550 
551  double angle;
552 
553  while (ss >> angle) {
554  angles.push_back(angle);
555  if (ss.peek() == ',' || ss.peek() == ' ') {
556  ss.ignore();
557  }
558  }
559 
560  if (!m_confParam.setCorR(radius)) {
561  return false;
562  }
563  m_confParam.setCorTheta(angles);
564  }
565  catch (const std::exception& ex) {
566  std::cerr << ex.what() << std::endl;
567  if (state == "on" || state == "dry-run") {
568  return false;
569  }
570  }
571 
572  return true;
573 }
574 
575 bool
576 ConfFileProcessor::processConfSectionFib(const ConfigSection& section)
577 {
578  // max-faces-per-prefix
579  int maxFacesPerPrefix = section.get<int>("max-faces-per-prefix", MAX_FACES_PER_PREFIX_DEFAULT);
580 
581  if (maxFacesPerPrefix >= MAX_FACES_PER_PREFIX_MIN &&
582  maxFacesPerPrefix <= MAX_FACES_PER_PREFIX_MAX)
583  {
584  m_confParam.setMaxFacesPerPrefix(maxFacesPerPrefix);
585  }
586  else {
587  std::cerr << "Wrong value for max-faces-per-prefix. ";
588  std::cerr << MAX_FACES_PER_PREFIX_MIN << std::endl;
589 
590  return false;
591  }
592 
593  // routing-calc-interval
594  ConfigurationVariable<uint32_t> routingCalcInterval("routing-calc-interval",
596  &m_confParam, _1));
598  routingCalcInterval.setOptional(ROUTING_CALC_INTERVAL_DEFAULT);
599 
600  if (!routingCalcInterval.parseFromConfigSection(section)) {
601  return false;
602  }
603 
604  return true;
605 }
606 
607 bool
608 ConfFileProcessor::processConfSectionAdvertising(const ConfigSection& section)
609 {
610  for (ConfigSection::const_iterator tn =
611  section.begin(); tn != section.end(); ++tn) {
612  if (tn->first == "prefix") {
613  try {
614  std::string prefix = tn->second.data();
615  ndn::Name namePrefix(prefix);
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  using namespace boost::filesystem;
652 
653  if (it->first != "cert-to-publish") {
654  std::cerr << "Error: Expect cert-to-publish!" << std::endl;
655  return false;
656  }
657 
658  std::string file = it->second.data();
659  path certfilePath = absolute(file, path(m_confFileName).parent_path());
660  std::shared_ptr<ndn::security::v2::Certificate> idCert =
661  ndn::io::load<ndn::security::v2::Certificate>(certfilePath.string());
662 
663  if (idCert == nullptr) {
664  std::cerr << "Error: Cannot load cert-to-publish: " << file << "!" << std::endl;
665  return false;
666  }
667 
668  m_confParam.getCertStore().insert(*idCert);
669  m_confParam.getValidator().loadAnchor("Authoritative-Certificate",
670  ndn::security::v2::Certificate(*idCert));
671  m_confParam.getPrefixUpdateValidator().loadAnchor("Authoritative-Certificate",
672  ndn::security::v2::Certificate(*idCert));
673  }
674  }
675 
676  return true;
677 }
678 
679 } // namespace nlsr
ndn::security::ValidatorConfig & getValidator()
A class to house all the configuration parameters for NLSR.
void setLsaInterestLifetime(const ndn::time::seconds &lifetime)
static const float DEFAULT_LINK_COST
Definition: adjacent.hpp:164
void setStateFileDir(const std::string &ssfd)
void setMaxFacesPerPrefix(uint32_t mfpp)
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)
boost::property_tree::ptree ConfigSection
void setRouterName(const ndn::Name &routerName)
void setFaceDatasetFetchInterval(uint32_t interval)
uint32_t getLsaRefreshTime() const
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
bool setCorR(double cr)
void setOptional(T defaultValue)
Copyright (c) 2014-2018, 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 setFirstHelloInterval(uint32_t interval)
void setLsaRefreshTime(uint32_t lrt)
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.