JSONDB.cpp 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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. #define ZT_JSONDB_HTTP_TIMEOUT 60000
  20. namespace ZeroTier {
  21. static const nlohmann::json _EMPTY_JSON(nlohmann::json::object());
  22. static const std::map<std::string,std::string> _ZT_JSONDB_GET_HEADERS;
  23. JSONDB::JSONDB(const std::string &basePath) :
  24. _basePath(basePath),
  25. _ready(false)
  26. {
  27. if ((_basePath.length() > 7)&&(_basePath.substr(0,7) == "http://")) {
  28. // TODO: this doesn't yet support IPv6 since bracketed address notiation isn't supported.
  29. // Typically it's used with 127.0.0.1 anyway.
  30. std::string hn = _basePath.substr(7);
  31. std::size_t hnend = hn.find_first_of('/');
  32. if (hnend != std::string::npos)
  33. hn = hn.substr(0,hnend);
  34. std::size_t hnsep = hn.find_last_of(':');
  35. if (hnsep != std::string::npos)
  36. hn[hnsep] = '/';
  37. _httpAddr.fromString(hn);
  38. if (hnend != std::string::npos)
  39. _basePath = _basePath.substr(7 + hnend);
  40. if (_basePath.length() == 0)
  41. _basePath = "/";
  42. if (_basePath[0] != '/')
  43. _basePath = std::string("/") + _basePath;
  44. } else {
  45. OSUtils::mkdir(_basePath.c_str());
  46. OSUtils::lockDownFile(_basePath.c_str(),true); // networks might contain auth tokens, etc., so restrict directory permissions
  47. }
  48. _ready = _reload(_basePath,std::string());
  49. }
  50. bool JSONDB::writeRaw(const std::string &n,const std::string &obj)
  51. {
  52. if (!_isValidObjectName(n))
  53. return false;
  54. if (_httpAddr) {
  55. std::map<std::string,std::string> headers;
  56. std::string body;
  57. std::map<std::string,std::string> reqHeaders;
  58. char tmp[64];
  59. Utils::snprintf(tmp,sizeof(tmp),"%lu",(unsigned long)obj.length());
  60. reqHeaders["Content-Length"] = tmp;
  61. reqHeaders["Content-Type"] = "application/json";
  62. const unsigned int sc = Http::PUT(1048576,ZT_JSONDB_HTTP_TIMEOUT,reinterpret_cast<const struct sockaddr *>(&_httpAddr),(_basePath+"/"+n).c_str(),reqHeaders,obj.data(),(unsigned long)obj.length(),headers,body);
  63. return (sc == 200);
  64. } else {
  65. const std::string path(_genPath(n,true));
  66. if (!path.length())
  67. return false;
  68. return OSUtils::writeFile(path.c_str(),obj);
  69. }
  70. }
  71. bool JSONDB::put(const std::string &n,const nlohmann::json &obj)
  72. {
  73. const bool r = writeRaw(n,OSUtils::jsonDump(obj));
  74. _db[n].obj = obj;
  75. return r;
  76. }
  77. const nlohmann::json &JSONDB::get(const std::string &n)
  78. {
  79. while (!_ready) {
  80. Thread::sleep(250);
  81. _ready = _reload(_basePath,std::string());
  82. }
  83. if (!_isValidObjectName(n))
  84. return _EMPTY_JSON;
  85. std::map<std::string,_E>::iterator e(_db.find(n));
  86. if (e != _db.end())
  87. return e->second.obj;
  88. std::string buf;
  89. if (_httpAddr) {
  90. std::map<std::string,std::string> headers;
  91. const unsigned int sc = Http::GET(1048576,ZT_JSONDB_HTTP_TIMEOUT,reinterpret_cast<const struct sockaddr *>(&_httpAddr),(_basePath+"/"+n).c_str(),_ZT_JSONDB_GET_HEADERS,headers,buf);
  92. if (sc != 200)
  93. return _EMPTY_JSON;
  94. } else {
  95. const std::string path(_genPath(n,false));
  96. if (!path.length())
  97. return _EMPTY_JSON;
  98. if (!OSUtils::readFile(path.c_str(),buf))
  99. return _EMPTY_JSON;
  100. }
  101. try {
  102. _E &e2 = _db[n];
  103. e2.obj = OSUtils::jsonParse(buf);
  104. return e2.obj;
  105. } catch ( ... ) {
  106. _db.erase(n);
  107. return _EMPTY_JSON;
  108. }
  109. }
  110. void JSONDB::erase(const std::string &n)
  111. {
  112. if (!_isValidObjectName(n))
  113. return;
  114. if (_httpAddr) {
  115. std::string body;
  116. std::map<std::string,std::string> headers;
  117. Http::DEL(1048576,ZT_JSONDB_HTTP_TIMEOUT,reinterpret_cast<const struct sockaddr *>(&_httpAddr),(_basePath+"/"+n).c_str(),_ZT_JSONDB_GET_HEADERS,headers,body);
  118. } else {
  119. std::string path(_genPath(n,true));
  120. if (!path.length())
  121. return;
  122. OSUtils::rm(path.c_str());
  123. }
  124. _db.erase(n);
  125. }
  126. bool JSONDB::_reload(const std::string &p,const std::string &b)
  127. {
  128. if (_httpAddr) {
  129. std::string body;
  130. std::map<std::string,std::string> headers;
  131. const unsigned int sc = Http::GET(2147483647,ZT_JSONDB_HTTP_TIMEOUT,reinterpret_cast<const struct sockaddr *>(&_httpAddr),_basePath.c_str(),_ZT_JSONDB_GET_HEADERS,headers,body);
  132. if (sc == 200) {
  133. try {
  134. nlohmann::json dbImg(OSUtils::jsonParse(body));
  135. std::string tmp;
  136. if (dbImg.is_object()) {
  137. for(nlohmann::json::iterator i(dbImg.begin());i!=dbImg.end();++i) {
  138. if (i.value().is_object()) {
  139. tmp = i.key();
  140. _db[tmp].obj = i.value();
  141. }
  142. }
  143. return true;
  144. }
  145. } catch ( ... ) {} // invalid JSON, so maybe incomplete request
  146. }
  147. return false;
  148. } else {
  149. std::vector<std::string> dl(OSUtils::listDirectory(p.c_str(),true));
  150. for(std::vector<std::string>::const_iterator di(dl.begin());di!=dl.end();++di) {
  151. if ((di->length() > 5)&&(di->substr(di->length() - 5) == ".json")) {
  152. this->get(b + di->substr(0,di->length() - 5));
  153. } else {
  154. this->_reload((p + ZT_PATH_SEPARATOR + *di),(b + *di + ZT_PATH_SEPARATOR));
  155. }
  156. }
  157. return true;
  158. }
  159. }
  160. bool JSONDB::_isValidObjectName(const std::string &n)
  161. {
  162. if (n.length() == 0)
  163. return false;
  164. const char *p = n.c_str();
  165. char c;
  166. // For security reasons we should not allow dots, backslashes, or other path characters or potential path characters.
  167. while ((c = *(p++))) {
  168. if (!( ((c >= 'a')&&(c <= 'z')) || ((c >= 'A')&&(c <= 'Z')) || ((c >= '0')&&(c <= '9')) || (c == '/') || (c == '_') || (c == '~') || (c == '-') ))
  169. return false;
  170. }
  171. return true;
  172. }
  173. std::string JSONDB::_genPath(const std::string &n,bool create)
  174. {
  175. std::vector<std::string> pt(OSUtils::split(n.c_str(),"/","",""));
  176. if (pt.size() == 0)
  177. return std::string();
  178. char sep;
  179. if (_httpAddr) {
  180. sep = '/';
  181. create = false;
  182. } else {
  183. sep = ZT_PATH_SEPARATOR;
  184. }
  185. std::string p(_basePath);
  186. if (create) OSUtils::mkdir(p.c_str());
  187. for(unsigned long i=0,j=(unsigned long)(pt.size()-1);i<j;++i) {
  188. p.push_back(sep);
  189. p.append(pt[i]);
  190. if (create) OSUtils::mkdir(p.c_str());
  191. }
  192. p.push_back(sep);
  193. p.append(pt[pt.size()-1]);
  194. p.append(".json");
  195. return p;
  196. }
  197. } // namespace ZeroTier