JSONDB.cpp 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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. {
  75. Mutex::Lock _l(_db_m);
  76. _db[n].obj = obj;
  77. }
  78. return r;
  79. }
  80. nlohmann::json JSONDB::get(const std::string &n)
  81. {
  82. {
  83. Mutex::Lock _l(_db_m);
  84. while (!_ready) {
  85. Thread::sleep(250);
  86. _ready = _reload(_basePath,std::string());
  87. }
  88. if (!_isValidObjectName(n))
  89. return _EMPTY_JSON;
  90. std::map<std::string,_E>::iterator e(_db.find(n));
  91. if (e != _db.end())
  92. return e->second.obj;
  93. }
  94. std::string buf;
  95. if (_httpAddr) {
  96. std::map<std::string,std::string> headers;
  97. 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);
  98. if (sc != 200)
  99. return _EMPTY_JSON;
  100. } else {
  101. const std::string path(_genPath(n,false));
  102. if (!path.length())
  103. return _EMPTY_JSON;
  104. if (!OSUtils::readFile(path.c_str(),buf))
  105. return _EMPTY_JSON;
  106. }
  107. try {
  108. Mutex::Lock _l(_db_m);
  109. _E &e2 = _db[n];
  110. e2.obj = OSUtils::jsonParse(buf);
  111. return e2.obj;
  112. } catch ( ... ) {
  113. _db.erase(n);
  114. return _EMPTY_JSON;
  115. }
  116. }
  117. void JSONDB::erase(const std::string &n)
  118. {
  119. if (!_isValidObjectName(n))
  120. return;
  121. if (_httpAddr) {
  122. std::string body;
  123. std::map<std::string,std::string> headers;
  124. Http::DEL(1048576,ZT_JSONDB_HTTP_TIMEOUT,reinterpret_cast<const struct sockaddr *>(&_httpAddr),(_basePath+"/"+n).c_str(),_ZT_JSONDB_GET_HEADERS,headers,body);
  125. } else {
  126. std::string path(_genPath(n,true));
  127. if (!path.length())
  128. return;
  129. OSUtils::rm(path.c_str());
  130. }
  131. {
  132. Mutex::Lock _l(_db_m);
  133. _db.erase(n);
  134. }
  135. }
  136. bool JSONDB::_reload(const std::string &p,const std::string &b)
  137. {
  138. // Assumes _db_m is locked
  139. if (_httpAddr) {
  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. for(nlohmann::json::iterator i(dbImg.begin());i!=dbImg.end();++i) {
  149. if (i.value().is_object()) {
  150. tmp = i.key();
  151. _db[tmp].obj = i.value();
  152. }
  153. }
  154. return true;
  155. }
  156. } catch ( ... ) {} // invalid JSON, so maybe incomplete request
  157. }
  158. return false;
  159. } else {
  160. std::vector<std::string> dl(OSUtils::listDirectory(p.c_str(),true));
  161. for(std::vector<std::string>::const_iterator di(dl.begin());di!=dl.end();++di) {
  162. if ((di->length() > 5)&&(di->substr(di->length() - 5) == ".json")) {
  163. this->get(b + di->substr(0,di->length() - 5));
  164. } else {
  165. this->_reload((p + ZT_PATH_SEPARATOR + *di),(b + *di + ZT_PATH_SEPARATOR));
  166. }
  167. }
  168. return true;
  169. }
  170. }
  171. bool JSONDB::_isValidObjectName(const std::string &n)
  172. {
  173. if (n.length() == 0)
  174. return false;
  175. const char *p = n.c_str();
  176. char c;
  177. // For security reasons we should not allow dots, backslashes, or other path characters or potential path characters.
  178. while ((c = *(p++))) {
  179. if (!( ((c >= 'a')&&(c <= 'z')) || ((c >= 'A')&&(c <= 'Z')) || ((c >= '0')&&(c <= '9')) || (c == '/') || (c == '_') || (c == '~') || (c == '-') ))
  180. return false;
  181. }
  182. return true;
  183. }
  184. std::string JSONDB::_genPath(const std::string &n,bool create)
  185. {
  186. std::vector<std::string> pt(OSUtils::split(n.c_str(),"/","",""));
  187. if (pt.size() == 0)
  188. return std::string();
  189. char sep;
  190. if (_httpAddr) {
  191. sep = '/';
  192. create = false;
  193. } else {
  194. sep = ZT_PATH_SEPARATOR;
  195. }
  196. std::string p(_basePath);
  197. if (create) OSUtils::mkdir(p.c_str());
  198. for(unsigned long i=0,j=(unsigned long)(pt.size()-1);i<j;++i) {
  199. p.push_back(sep);
  200. p.append(pt[i]);
  201. if (create) OSUtils::mkdir(p.c_str());
  202. }
  203. p.push_back(sep);
  204. p.append(pt[pt.size()-1]);
  205. p.append(".json");
  206. return p;
  207. }
  208. } // namespace ZeroTier