EmbeddedNetworkController.hpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. #ifndef ZT_SQLITENETWORKCONTROLLER_HPP
  19. #define ZT_SQLITENETWORKCONTROLLER_HPP
  20. #include <stdint.h>
  21. #include <string>
  22. #include <map>
  23. #include <vector>
  24. #include <set>
  25. #include <list>
  26. #include <thread>
  27. #include <unordered_map>
  28. #include <atomic>
  29. #include "../node/Constants.hpp"
  30. #include "../node/NetworkController.hpp"
  31. #include "../node/Utils.hpp"
  32. #include "../node/Address.hpp"
  33. #include "../node/InetAddress.hpp"
  34. #include "../node/NonCopyable.hpp"
  35. #include "../osdep/OSUtils.hpp"
  36. #include "../osdep/Thread.hpp"
  37. #include "../osdep/BlockingQueue.hpp"
  38. #include "../ext/json/json.hpp"
  39. #ifdef ZT_CONTROLLER_USE_RETHINKDB
  40. #include "RethinkDB.hpp"
  41. #else
  42. #include "FileDB.hpp"
  43. #endif
  44. namespace ZeroTier {
  45. #ifdef ZT_CONTROLLER_USE_RETHINKDB
  46. typedef RethinkDB ControllerDB;
  47. #else
  48. typedef FileDB ControllerDB;
  49. #endif
  50. class Node;
  51. class EmbeddedNetworkController : public NetworkController
  52. {
  53. public:
  54. /**
  55. * @param node Parent node
  56. * @param dbPath Database path (file path or database credentials)
  57. */
  58. EmbeddedNetworkController(Node *node,const char *dbPath);
  59. virtual ~EmbeddedNetworkController();
  60. virtual void init(const Identity &signingId,Sender *sender);
  61. virtual void request(
  62. uint64_t nwid,
  63. const InetAddress &fromAddr,
  64. uint64_t requestPacketId,
  65. const Identity &identity,
  66. const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> &metaData);
  67. unsigned int handleControlPlaneHttpGET(
  68. const std::vector<std::string> &path,
  69. const std::map<std::string,std::string> &urlArgs,
  70. const std::map<std::string,std::string> &headers,
  71. const std::string &body,
  72. std::string &responseBody,
  73. std::string &responseContentType);
  74. unsigned int handleControlPlaneHttpPOST(
  75. const std::vector<std::string> &path,
  76. const std::map<std::string,std::string> &urlArgs,
  77. const std::map<std::string,std::string> &headers,
  78. const std::string &body,
  79. std::string &responseBody,
  80. std::string &responseContentType);
  81. unsigned int handleControlPlaneHttpDELETE(
  82. const std::vector<std::string> &path,
  83. const std::map<std::string,std::string> &urlArgs,
  84. const std::map<std::string,std::string> &headers,
  85. const std::string &body,
  86. std::string &responseBody,
  87. std::string &responseContentType);
  88. void handleRemoteTrace(const ZT_RemoteTrace &rt);
  89. // Called on update via POST or by JSONDB on external update of network or network member records
  90. void onNetworkUpdate(const uint64_t networkId);
  91. void onNetworkMemberUpdate(const uint64_t networkId,const uint64_t memberId);
  92. void onNetworkMemberDeauthorize(const uint64_t networkId,const uint64_t memberId);
  93. private:
  94. void _request(uint64_t nwid,const InetAddress &fromAddr,uint64_t requestPacketId,const Identity &identity,const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> &metaData);
  95. void _startThreads();
  96. // These init objects with default and static/informational fields
  97. inline void _initMember(nlohmann::json &member)
  98. {
  99. if (!member.count("authorized")) member["authorized"] = false;
  100. if (!member.count("ipAssignments")) member["ipAssignments"] = nlohmann::json::array();
  101. if (!member.count("activeBridge")) member["activeBridge"] = false;
  102. if (!member.count("tags")) member["tags"] = nlohmann::json::array();
  103. if (!member.count("capabilities")) member["capabilities"] = nlohmann::json::array();
  104. if (!member.count("creationTime")) member["creationTime"] = OSUtils::now();
  105. if (!member.count("noAutoAssignIps")) member["noAutoAssignIps"] = false;
  106. if (!member.count("revision")) member["revision"] = 0ULL;
  107. if (!member.count("lastDeauthorizedTime")) member["lastDeauthorizedTime"] = 0ULL;
  108. if (!member.count("lastAuthorizedTime")) member["lastAuthorizedTime"] = 0ULL;
  109. if (!member.count("lastAuthorizedCredentialType")) member["lastAuthorizedCredentialType"] = nlohmann::json();
  110. if (!member.count("lastAuthorizedCredential")) member["lastAuthorizedCredential"] = nlohmann::json();
  111. if (!member.count("vMajor")) member["vMajor"] = -1;
  112. if (!member.count("vMinor")) member["vMinor"] = -1;
  113. if (!member.count("vRev")) member["vRev"] = -1;
  114. if (!member.count("vProto")) member["vProto"] = -1;
  115. if (!member.count("physicalAddr")) member["physicalAddr"] = nlohmann::json();
  116. if (!member.count("remoteTraceTarget")) member["remoteTraceTarget"] = nlohmann::json();
  117. member["objtype"] = "member";
  118. }
  119. inline void _initNetwork(nlohmann::json &network)
  120. {
  121. if (!network.count("private")) network["private"] = true;
  122. if (!network.count("creationTime")) network["creationTime"] = OSUtils::now();
  123. if (!network.count("name")) network["name"] = "";
  124. if (!network.count("multicastLimit")) network["multicastLimit"] = (uint64_t)32;
  125. if (!network.count("enableBroadcast")) network["enableBroadcast"] = true;
  126. if (!network.count("v4AssignMode")) network["v4AssignMode"] = {{"zt",false}};
  127. if (!network.count("v6AssignMode")) network["v6AssignMode"] = {{"rfc4193",false},{"zt",false},{"6plane",false}};
  128. if (!network.count("authTokens")) network["authTokens"] = {{}};
  129. if (!network.count("capabilities")) network["capabilities"] = nlohmann::json::array();
  130. if (!network.count("tags")) network["tags"] = nlohmann::json::array();
  131. if (!network.count("routes")) network["routes"] = nlohmann::json::array();
  132. if (!network.count("ipAssignmentPools")) network["ipAssignmentPools"] = nlohmann::json::array();
  133. if (!network.count("mtu")) network["mtu"] = ZT_DEFAULT_MTU;
  134. if (!network.count("remoteTraceTarget")) network["remoteTraceTarget"] = nlohmann::json();
  135. if (!network.count("rules")) {
  136. // If unspecified, rules are set to allow anything and behave like a flat L2 segment
  137. network["rules"] = {{
  138. { "not",false },
  139. { "or", false },
  140. { "type","ACTION_ACCEPT" }
  141. }};
  142. }
  143. network["objtype"] = "network";
  144. }
  145. inline void _addNetworkNonPersistedFields(const uint64_t nwid,nlohmann::json &network,int64_t now,const ControllerDB::NetworkSummaryInfo &ns)
  146. {
  147. network["clock"] = now;
  148. network["authorizedMemberCount"] = ns.authorizedMemberCount;
  149. network["totalMemberCount"] = ns.totalMemberCount;
  150. {
  151. std::lock_guard<std::mutex> l(_memberStatus_l);
  152. unsigned long ac = 0;
  153. for(auto ms=_memberStatus.begin();ms!=_memberStatus.end();++ms) {
  154. if ((ms->first.networkId == nwid)&&(ms->second.online(now)))
  155. ++ac;
  156. }
  157. network["activeMemberCount"] = ac;
  158. }
  159. }
  160. inline void _removeNetworkNonPersistedFields(nlohmann::json &network)
  161. {
  162. network.erase("clock");
  163. network.erase("authorizedMemberCount");
  164. network.erase("activeMemberCount");
  165. network.erase("totalMemberCount");
  166. // legacy fields
  167. network.erase("lastModified");
  168. }
  169. inline void _addMemberNonPersistedFields(uint64_t nwid,uint64_t nodeId,nlohmann::json &member,int64_t now)
  170. {
  171. member["clock"] = now;
  172. {
  173. std::lock_guard<std::mutex> l(_memberStatus_l);
  174. member["online"] = _memberStatus[_MemberStatusKey(nwid,nodeId)].online(now);
  175. }
  176. }
  177. inline void _removeMemberNonPersistedFields(nlohmann::json &member)
  178. {
  179. member.erase("clock");
  180. // legacy fields
  181. member.erase("recentLog");
  182. member.erase("lastModified");
  183. member.erase("lastRequestMetaData");
  184. }
  185. struct _RQEntry
  186. {
  187. uint64_t nwid;
  188. uint64_t requestPacketId;
  189. InetAddress fromAddr;
  190. Identity identity;
  191. Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> metaData;
  192. enum {
  193. RQENTRY_TYPE_REQUEST = 0
  194. } type;
  195. };
  196. struct _MemberStatusKey
  197. {
  198. _MemberStatusKey() : networkId(0),nodeId(0) {}
  199. _MemberStatusKey(const uint64_t nwid,const uint64_t nid) : networkId(nwid),nodeId(nid) {}
  200. uint64_t networkId;
  201. uint64_t nodeId;
  202. inline bool operator==(const _MemberStatusKey &k) const { return ((k.networkId == networkId)&&(k.nodeId == nodeId)); }
  203. };
  204. struct _MemberStatus
  205. {
  206. _MemberStatus() : lastRequestTime(0),vMajor(-1),vMinor(-1),vRev(-1),vProto(-1) {}
  207. uint64_t lastRequestTime;
  208. int vMajor,vMinor,vRev,vProto;
  209. Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> lastRequestMetaData;
  210. Identity identity;
  211. InetAddress physicalAddr; // last known physical address
  212. inline bool online(const int64_t now) const { return ((now - lastRequestTime) < (ZT_NETWORK_AUTOCONF_DELAY * 2)); }
  213. };
  214. struct _MemberStatusHash
  215. {
  216. inline std::size_t operator()(const _MemberStatusKey &networkIdNodeId) const
  217. {
  218. return (std::size_t)(networkIdNodeId.networkId + networkIdNodeId.nodeId);
  219. }
  220. };
  221. const int64_t _startTime;
  222. Node *const _node;
  223. std::string _path;
  224. Identity _signingId;
  225. std::string _signingIdAddressString;
  226. NetworkController::Sender *_sender;
  227. std::unique_ptr<ControllerDB> _db;
  228. BlockingQueue< _RQEntry * > _queue;
  229. std::vector<std::thread> _threads;
  230. std::mutex _threads_l;
  231. std::unordered_map< _MemberStatusKey,_MemberStatus,_MemberStatusHash > _memberStatus;
  232. std::mutex _memberStatus_l;
  233. };
  234. } // namespace ZeroTier
  235. #endif