EmbeddedNetworkController.hpp 9.1 KB

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