JSONDB.cpp 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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. _reload(_basePath,std::string());
  49. }
  50. bool JSONDB::writeRaw(const std::string &n,const std::string &obj)
  51. {
  52. if (_httpAddr) {
  53. std::map<std::string,std::string> headers;
  54. std::string body;
  55. std::map<std::string,std::string> reqHeaders;
  56. char tmp[64];
  57. Utils::snprintf(tmp,sizeof(tmp),"%lu",(unsigned long)obj.length());
  58. reqHeaders["Content-Length"] = tmp;
  59. reqHeaders["Content-Type"] = "application/json";
  60. 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);
  61. return (sc == 200);
  62. } else {
  63. const std::string path(_genPath(n,true));
  64. if (!path.length())
  65. return false;
  66. return OSUtils::writeFile(path.c_str(),obj);
  67. }
  68. }
  69. bool JSONDB::put(const std::string &n,const nlohmann::json &obj)
  70. {
  71. const bool r = writeRaw(n,OSUtils::jsonDump(obj));
  72. {
  73. Mutex::Lock _l(_db_m);
  74. _db[n].obj = obj;
  75. }
  76. return r;
  77. }
  78. nlohmann::json JSONDB::get(const std::string &n)
  79. {
  80. while (!_ready) {
  81. Thread::sleep(250);
  82. _reload(_basePath,std::string());
  83. }
  84. {
  85. Mutex::Lock _l(_db_m);
  86. std::map<std::string,_E>::iterator e(_db.find(n));
  87. if (e != _db.end())
  88. return e->second.obj;
  89. }
  90. std::string buf;
  91. if (_httpAddr) {
  92. std::map<std::string,std::string> headers;
  93. 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);
  94. if (sc != 200)
  95. return _EMPTY_JSON;
  96. } else {
  97. const std::string path(_genPath(n,false));
  98. if (!path.length())
  99. return _EMPTY_JSON;
  100. if (!OSUtils::readFile(path.c_str(),buf))
  101. return _EMPTY_JSON;
  102. }
  103. {
  104. Mutex::Lock _l(_db_m);
  105. try {
  106. _E &e2 = _db[n];
  107. e2.obj = OSUtils::jsonParse(buf);
  108. return e2.obj;
  109. } catch ( ... ) {
  110. _db.erase(n);
  111. return _EMPTY_JSON;
  112. }
  113. }
  114. }
  115. void JSONDB::erase(const std::string &n)
  116. {
  117. _erase(n);
  118. {
  119. Mutex::Lock _l(_db_m);
  120. _db.erase(n);
  121. }
  122. }
  123. void JSONDB::_erase(const std::string &n)
  124. {
  125. if (_httpAddr) {
  126. std::string body;
  127. std::map<std::string,std::string> headers;
  128. Http::DEL(1048576,ZT_JSONDB_HTTP_TIMEOUT,reinterpret_cast<const struct sockaddr *>(&_httpAddr),(_basePath+"/"+n).c_str(),_ZT_JSONDB_GET_HEADERS,headers,body);
  129. } else {
  130. std::string path(_genPath(n,true));
  131. if (!path.length())
  132. return;
  133. OSUtils::rm(path.c_str());
  134. }
  135. }
  136. void JSONDB::_reload(const std::string &p,const std::string &b)
  137. {
  138. if (_httpAddr) {
  139. Mutex::Lock _l(_db_m);
  140. std::string body;
  141. std::map<std::string,std::string> headers;
  142. 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);
  143. if (sc == 200) {
  144. try {
  145. nlohmann::json dbImg(OSUtils::jsonParse(body));
  146. std::string tmp;
  147. if (dbImg.is_object()) {
  148. _db.clear();
  149. for(nlohmann::json::iterator i(dbImg.begin());i!=dbImg.end();++i) {
  150. if (i.value().is_object()) {
  151. tmp = i.key();
  152. _db[tmp].obj = i.value();
  153. }
  154. }
  155. _ready = true;
  156. }
  157. } catch ( ... ) {} // invalid JSON, so maybe incomplete request
  158. }
  159. } else {
  160. _ready = true;
  161. std::vector<std::string> dl(OSUtils::listDirectory(p.c_str(),true));
  162. for(std::vector<std::string>::const_iterator di(dl.begin());di!=dl.end();++di) {
  163. if ((di->length() > 5)&&(di->substr(di->length() - 5) == ".json")) {
  164. this->get(b + di->substr(0,di->length() - 5));
  165. } else {
  166. this->_reload((p + ZT_PATH_SEPARATOR + *di),(b + *di + ZT_PATH_SEPARATOR));
  167. }
  168. }
  169. }
  170. }
  171. std::string JSONDB::_genPath(const std::string &n,bool create)
  172. {
  173. std::vector<std::string> pt(OSUtils::split(n.c_str(),"/","",""));
  174. if (pt.size() == 0)
  175. return std::string();
  176. char sep;
  177. if (_httpAddr) {
  178. sep = '/';
  179. create = false;
  180. } else {
  181. sep = ZT_PATH_SEPARATOR;
  182. }
  183. std::string p(_basePath);
  184. if (create) OSUtils::mkdir(p.c_str());
  185. for(unsigned long i=0,j=(unsigned long)(pt.size()-1);i<j;++i) {
  186. p.push_back(sep);
  187. p.append(pt[i]);
  188. if (create) OSUtils::mkdir(p.c_str());
  189. }
  190. p.push_back(sep);
  191. p.append(pt[pt.size()-1]);
  192. p.append(".json");
  193. return p;
  194. }
  195. } // namespace ZeroTier