JSONDB.cpp 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #include "JSONDB.hpp"
  19. namespace ZeroTier {
  20. static const nlohmann::json _EMPTY_JSON(nlohmann::json::object());
  21. bool JSONDB::put(const std::string &n,const nlohmann::json &obj)
  22. {
  23. if (!_isValidObjectName(n))
  24. return false;
  25. const std::string path(_genPath(n,true));
  26. if (!path.length())
  27. return false;
  28. const std::string buf(obj.dump(2));
  29. if (!OSUtils::writeFile(path.c_str(),buf))
  30. return false;
  31. if (_feed)
  32. fwrite(buf.c_str(),buf.length()+1,1,_feed);
  33. _E &e = _db[n];
  34. e.obj = obj;
  35. e.lastModifiedOnDisk = OSUtils::getLastModified(path.c_str());
  36. e.lastCheck = OSUtils::now();
  37. return true;
  38. }
  39. const nlohmann::json &JSONDB::get(const std::string &n,unsigned long maxSinceCheck)
  40. {
  41. if (!_isValidObjectName(n))
  42. return _EMPTY_JSON;
  43. const uint64_t now = OSUtils::now();
  44. std::string buf;
  45. std::map<std::string,_E>::iterator e(_db.find(n));
  46. if (e != _db.end()) {
  47. if ((now - e->second.lastCheck) <= (uint64_t)maxSinceCheck)
  48. return e->second.obj;
  49. const std::string path(_genPath(n,false));
  50. if (!path.length()) // sanity check
  51. return _EMPTY_JSON;
  52. // We are somewhat tolerant to momentary disk failures here. This may
  53. // occur over e.g. EC2's elastic filesystem (NFS).
  54. const uint64_t lm = OSUtils::getLastModified(path.c_str());
  55. if (e->second.lastModifiedOnDisk != lm) {
  56. if (OSUtils::readFile(path.c_str(),buf)) {
  57. try {
  58. e->second.obj = nlohmann::json::parse(buf);
  59. e->second.lastModifiedOnDisk = lm; // don't update these if there is a parse error -- try again and again ASAP
  60. e->second.lastCheck = now;
  61. if (_feed)
  62. fwrite(buf.c_str(),buf.length()+1,1,_feed); // it changed, so send to feed (also sends all objects on startup, which we want for Central)
  63. } catch ( ... ) {} // parse errors result in "holding pattern" behavior
  64. }
  65. }
  66. return e->second.obj;
  67. } else {
  68. const std::string path(_genPath(n,false));
  69. if (!path.length())
  70. return _EMPTY_JSON;
  71. if (!OSUtils::readFile(path.c_str(),buf))
  72. return _EMPTY_JSON;
  73. const uint64_t lm = OSUtils::getLastModified(path.c_str());
  74. _E &e2 = _db[n];
  75. try {
  76. e2.obj = nlohmann::json::parse(buf);
  77. } catch ( ... ) {
  78. e2.obj = _EMPTY_JSON;
  79. buf = "{}";
  80. }
  81. e2.lastModifiedOnDisk = lm;
  82. e2.lastCheck = now;
  83. if (_feed)
  84. fwrite(buf.c_str(),buf.length()+1,1,_feed);
  85. return e2.obj;
  86. }
  87. }
  88. void JSONDB::erase(const std::string &n)
  89. {
  90. if (!_isValidObjectName(n))
  91. return;
  92. std::string path(_genPath(n,true));
  93. if (!path.length())
  94. return;
  95. OSUtils::rm(path.c_str());
  96. _db.erase(n);
  97. }
  98. void JSONDB::_reload(const std::string &p)
  99. {
  100. std::map<std::string,char> l(OSUtils::listDirectoryFull(p.c_str()));
  101. for(std::map<std::string,char>::iterator li(l.begin());li!=l.end();++li) {
  102. if (li->second == 'f') {
  103. // assume p starts with _basePath, which it always does -- will throw otherwise
  104. std::string n(p.substr(_basePath.length()));
  105. while ((n.length() > 0)&&(n[0] == ZT_PATH_SEPARATOR)) n = n.substr(1);
  106. if (ZT_PATH_SEPARATOR != '/') std::replace(n.begin(),n.end(),ZT_PATH_SEPARATOR,'/');
  107. if ((n.length() > 0)&&(n[n.length() - 1] != '/')) n.push_back('/');
  108. n.append(li->first);
  109. if ((n.length() > 5)&&(n.substr(n.length() - 5) == ".json")) {
  110. this->get(n.substr(0,n.length() - 5),0); // causes load and cache or update
  111. }
  112. } else if (li->second == 'd') {
  113. this->_reload(p + ZT_PATH_SEPARATOR + li->first);
  114. }
  115. }
  116. }
  117. bool JSONDB::_isValidObjectName(const std::string &n)
  118. {
  119. if (n.length() == 0)
  120. return false;
  121. const char *p = n.c_str();
  122. char c;
  123. // For security reasons we should not allow dots, backslashes, or other path characters or potential path characters.
  124. while ((c = *(p++))) {
  125. if (!( ((c >= 'a')&&(c <= 'z')) || ((c >= 'A')&&(c <= 'Z')) || ((c >= '0')&&(c <= '9')) || (c == '/') || (c == '_') || (c == '~') || (c == '-') ))
  126. return false;
  127. }
  128. return true;
  129. }
  130. std::string JSONDB::_genPath(const std::string &n,bool create)
  131. {
  132. std::vector<std::string> pt(OSUtils::split(n.c_str(),"/","",""));
  133. if (pt.size() == 0)
  134. return std::string();
  135. std::string p(_basePath);
  136. if (create) OSUtils::mkdir(p.c_str());
  137. for(unsigned long i=0,j=pt.size()-1;i<j;++i) {
  138. p.push_back(ZT_PATH_SEPARATOR);
  139. p.append(pt[i]);
  140. if (create) OSUtils::mkdir(p.c_str());
  141. }
  142. p.push_back(ZT_PATH_SEPARATOR);
  143. p.append(pt[pt.size()-1]);
  144. p.append(".json");
  145. return p;
  146. }
  147. } // namespace ZeroTier