Node.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2017 ZeroTier, Inc. https://www.zerotier.com/
  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. * --
  19. *
  20. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #ifndef ZT_NODE_HPP
  27. #define ZT_NODE_HPP
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #include <map>
  32. #include <vector>
  33. #include "Constants.hpp"
  34. #include "../include/ZeroTierOne.h"
  35. #include "RuntimeEnvironment.hpp"
  36. #include "InetAddress.hpp"
  37. #include "Mutex.hpp"
  38. #include "MAC.hpp"
  39. #include "Network.hpp"
  40. #include "Path.hpp"
  41. #include "Salsa20.hpp"
  42. #include "NetworkController.hpp"
  43. #undef TRACE
  44. #ifdef ZT_TRACE
  45. #define TRACE(f,...) RR->node->postTrace(__FILE__,__LINE__,f,##__VA_ARGS__)
  46. #else
  47. #define TRACE(f,...) {}
  48. #endif
  49. // Bit mask for "expecting reply" hash
  50. #define ZT_EXPECTING_REPLIES_BUCKET_MASK1 255
  51. #define ZT_EXPECTING_REPLIES_BUCKET_MASK2 31
  52. namespace ZeroTier {
  53. class World;
  54. /**
  55. * Implementation of Node object as defined in CAPI
  56. *
  57. * The pointer returned by ZT_Node_new() is an instance of this class.
  58. */
  59. class Node : public NetworkController::Sender
  60. {
  61. public:
  62. Node(void *uptr,void *tptr,const struct ZT_Node_Callbacks *callbacks,uint64_t now);
  63. virtual ~Node();
  64. // Get rid of alignment warnings on 32-bit Windows and possibly improve performance
  65. #ifdef __WINDOWS__
  66. void * operator new(size_t i) { return _mm_malloc(i,16); }
  67. void operator delete(void* p) { _mm_free(p); }
  68. #endif
  69. // Public API Functions ----------------------------------------------------
  70. ZT_ResultCode processWirePacket(
  71. void *tptr,
  72. uint64_t now,
  73. const struct sockaddr_storage *localAddress,
  74. const struct sockaddr_storage *remoteAddress,
  75. const void *packetData,
  76. unsigned int packetLength,
  77. volatile uint64_t *nextBackgroundTaskDeadline);
  78. ZT_ResultCode processVirtualNetworkFrame(
  79. void *tptr,
  80. uint64_t now,
  81. uint64_t nwid,
  82. uint64_t sourceMac,
  83. uint64_t destMac,
  84. unsigned int etherType,
  85. unsigned int vlanId,
  86. const void *frameData,
  87. unsigned int frameLength,
  88. volatile uint64_t *nextBackgroundTaskDeadline);
  89. ZT_ResultCode processBackgroundTasks(void *tptr,uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline);
  90. ZT_ResultCode join(uint64_t nwid,void *uptr,void *tptr);
  91. ZT_ResultCode leave(uint64_t nwid,void **uptr,void *tptr);
  92. ZT_ResultCode multicastSubscribe(void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi);
  93. ZT_ResultCode multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi);
  94. ZT_ResultCode orbit(void *tptr,uint64_t moonWorldId,uint64_t moonSeed);
  95. ZT_ResultCode deorbit(void *tptr,uint64_t moonWorldId);
  96. uint64_t address() const;
  97. void status(ZT_NodeStatus *status) const;
  98. ZT_PeerList *peers() const;
  99. ZT_VirtualNetworkConfig *networkConfig(uint64_t nwid) const;
  100. ZT_VirtualNetworkList *networks() const;
  101. void freeQueryResult(void *qr);
  102. int addLocalInterfaceAddress(const struct sockaddr_storage *addr);
  103. void clearLocalInterfaceAddresses();
  104. int sendUserMessage(void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len);
  105. void setNetconfMaster(void *networkControllerInstance);
  106. ZT_ResultCode circuitTestBegin(void *tptr,ZT_CircuitTest *test,void (*reportCallback)(ZT_Node *,ZT_CircuitTest *,const ZT_CircuitTestReport *));
  107. void circuitTestEnd(ZT_CircuitTest *test);
  108. ZT_ResultCode clusterInit(
  109. unsigned int myId,
  110. const struct sockaddr_storage *zeroTierPhysicalEndpoints,
  111. unsigned int numZeroTierPhysicalEndpoints,
  112. int x,
  113. int y,
  114. int z,
  115. void (*sendFunction)(void *,unsigned int,const void *,unsigned int),
  116. void *sendFunctionArg,
  117. int (*addressToLocationFunction)(void *,const struct sockaddr_storage *,int *,int *,int *),
  118. void *addressToLocationFunctionArg);
  119. ZT_ResultCode clusterAddMember(unsigned int memberId);
  120. void clusterRemoveMember(unsigned int memberId);
  121. void clusterHandleIncomingMessage(const void *msg,unsigned int len);
  122. void clusterStatus(ZT_ClusterStatus *cs);
  123. // Internal functions ------------------------------------------------------
  124. inline uint64_t now() const throw() { return _now; }
  125. inline bool putPacket(void *tPtr,const InetAddress &localAddress,const InetAddress &addr,const void *data,unsigned int len,unsigned int ttl = 0)
  126. {
  127. return (_cb.wirePacketSendFunction(
  128. reinterpret_cast<ZT_Node *>(this),
  129. _uPtr,
  130. tPtr,
  131. reinterpret_cast<const struct sockaddr_storage *>(&localAddress),
  132. reinterpret_cast<const struct sockaddr_storage *>(&addr),
  133. data,
  134. len,
  135. ttl) == 0);
  136. }
  137. inline void putFrame(void *tPtr,uint64_t nwid,void **nuptr,const MAC &source,const MAC &dest,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  138. {
  139. _cb.virtualNetworkFrameFunction(
  140. reinterpret_cast<ZT_Node *>(this),
  141. _uPtr,
  142. tPtr,
  143. nwid,
  144. nuptr,
  145. source.toInt(),
  146. dest.toInt(),
  147. etherType,
  148. vlanId,
  149. data,
  150. len);
  151. }
  152. inline SharedPtr<Network> network(uint64_t nwid) const
  153. {
  154. Mutex::Lock _l(_networks_m);
  155. return _network(nwid);
  156. }
  157. inline bool belongsToNetwork(uint64_t nwid) const
  158. {
  159. Mutex::Lock _l(_networks_m);
  160. for(std::vector< std::pair< uint64_t, SharedPtr<Network> > >::const_iterator i=_networks.begin();i!=_networks.end();++i) {
  161. if (i->first == nwid)
  162. return true;
  163. }
  164. return false;
  165. }
  166. inline std::vector< SharedPtr<Network> > allNetworks() const
  167. {
  168. std::vector< SharedPtr<Network> > nw;
  169. Mutex::Lock _l(_networks_m);
  170. nw.reserve(_networks.size());
  171. for(std::vector< std::pair< uint64_t, SharedPtr<Network> > >::const_iterator i=_networks.begin();i!=_networks.end();++i)
  172. nw.push_back(i->second);
  173. return nw;
  174. }
  175. inline std::vector<InetAddress> directPaths() const
  176. {
  177. Mutex::Lock _l(_directPaths_m);
  178. return _directPaths;
  179. }
  180. inline bool dataStorePut(void *tPtr,const char *name,const void *data,unsigned int len,bool secure) { return (_cb.dataStorePutFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,name,data,len,(int)secure) == 0); }
  181. inline bool dataStorePut(void *tPtr,const char *name,const std::string &data,bool secure) { return dataStorePut(tPtr,name,(const void *)data.data(),(unsigned int)data.length(),secure); }
  182. inline void dataStoreDelete(void *tPtr,const char *name) { _cb.dataStorePutFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,name,(const void *)0,0,0); }
  183. std::string dataStoreGet(void *tPtr,const char *name);
  184. inline void postEvent(void *tPtr,ZT_Event ev,const void *md = (const void *)0) { _cb.eventCallback(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,ev,md); }
  185. inline int configureVirtualNetworkPort(void *tPtr,uint64_t nwid,void **nuptr,ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nc) { return _cb.virtualNetworkConfigFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,nwid,nuptr,op,nc); }
  186. inline bool online() const throw() { return _online; }
  187. #ifdef ZT_TRACE
  188. void postTrace(const char *module,unsigned int line,const char *fmt,...);
  189. #endif
  190. bool shouldUsePathForZeroTierTraffic(void *tPtr,const Address &ztaddr,const InetAddress &localAddress,const InetAddress &remoteAddress);
  191. inline bool externalPathLookup(void *tPtr,const Address &ztaddr,int family,InetAddress &addr) { return ( (_cb.pathLookupFunction) ? (_cb.pathLookupFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,ztaddr.toInt(),family,reinterpret_cast<struct sockaddr_storage *>(&addr)) != 0) : false ); }
  192. uint64_t prng();
  193. void postCircuitTestReport(const ZT_CircuitTestReport *report);
  194. void setTrustedPaths(const struct sockaddr_storage *networks,const uint64_t *ids,unsigned int count);
  195. World planet() const;
  196. std::vector<World> moons() const;
  197. /**
  198. * Register that we are expecting a reply to a packet ID
  199. *
  200. * This only uses the most significant bits of the packet ID, both to save space
  201. * and to avoid using the higher bits that can be modified during armor() to
  202. * mask against the packet send counter used for QoS detection.
  203. *
  204. * @param packetId Packet ID to expect reply to
  205. */
  206. inline void expectReplyTo(const uint64_t packetId)
  207. {
  208. const unsigned long pid2 = (unsigned long)(packetId >> 32);
  209. const unsigned long bucket = (unsigned long)(pid2 & ZT_EXPECTING_REPLIES_BUCKET_MASK1);
  210. _expectingRepliesTo[bucket][_expectingRepliesToBucketPtr[bucket]++ & ZT_EXPECTING_REPLIES_BUCKET_MASK2] = (uint32_t)pid2;
  211. }
  212. /**
  213. * Check whether a given packet ID is something we are expecting a reply to
  214. *
  215. * This only uses the most significant bits of the packet ID, both to save space
  216. * and to avoid using the higher bits that can be modified during armor() to
  217. * mask against the packet send counter used for QoS detection.
  218. *
  219. * @param packetId Packet ID to check
  220. * @return True if we're expecting a reply
  221. */
  222. inline bool expectingReplyTo(const uint64_t packetId) const
  223. {
  224. const uint32_t pid2 = (uint32_t)(packetId >> 32);
  225. const unsigned long bucket = (unsigned long)(pid2 & ZT_EXPECTING_REPLIES_BUCKET_MASK1);
  226. for(unsigned long i=0;i<=ZT_EXPECTING_REPLIES_BUCKET_MASK2;++i) {
  227. if (_expectingRepliesTo[bucket][i] == pid2)
  228. return true;
  229. }
  230. return false;
  231. }
  232. /**
  233. * Check whether we should do potentially expensive identity verification (rate limit)
  234. *
  235. * @param now Current time
  236. * @param from Source address of packet
  237. * @return True if within rate limits
  238. */
  239. inline bool rateGateIdentityVerification(const uint64_t now,const InetAddress &from)
  240. {
  241. unsigned long iph = from.rateGateHash();
  242. if ((now - _lastIdentityVerification[iph]) >= ZT_IDENTITY_VALIDATION_SOURCE_RATE_LIMIT) {
  243. _lastIdentityVerification[iph] = now;
  244. return true;
  245. }
  246. return false;
  247. }
  248. virtual void ncSendConfig(uint64_t nwid,uint64_t requestPacketId,const Address &destination,const NetworkConfig &nc,bool sendLegacyFormatConfig);
  249. virtual void ncSendRevocation(const Address &destination,const Revocation &rev);
  250. virtual void ncSendError(uint64_t nwid,uint64_t requestPacketId,const Address &destination,NetworkController::ErrorCode errorCode);
  251. private:
  252. inline SharedPtr<Network> _network(uint64_t nwid) const
  253. {
  254. // assumes _networks_m is locked
  255. for(std::vector< std::pair< uint64_t, SharedPtr<Network> > >::const_iterator i=_networks.begin();i!=_networks.end();++i) {
  256. if (i->first == nwid)
  257. return i->second;
  258. }
  259. return SharedPtr<Network>();
  260. }
  261. RuntimeEnvironment _RR;
  262. RuntimeEnvironment *RR;
  263. void *_uPtr; // _uptr (lower case) is reserved in Visual Studio :P
  264. ZT_Node_Callbacks _cb;
  265. // For tracking packet IDs to filter out OK/ERROR replies to packets we did not send
  266. uint8_t _expectingRepliesToBucketPtr[ZT_EXPECTING_REPLIES_BUCKET_MASK1 + 1];
  267. uint32_t _expectingRepliesTo[ZT_EXPECTING_REPLIES_BUCKET_MASK1 + 1][ZT_EXPECTING_REPLIES_BUCKET_MASK2 + 1];
  268. // Time of last identity verification indexed by InetAddress.rateGateHash() -- used in IncomingPacket::_doHELLO() via rateGateIdentityVerification()
  269. uint64_t _lastIdentityVerification[16384];
  270. std::vector< std::pair< uint64_t, SharedPtr<Network> > > _networks;
  271. Mutex _networks_m;
  272. std::vector< ZT_CircuitTest * > _circuitTests;
  273. Mutex _circuitTests_m;
  274. std::vector<InetAddress> _directPaths;
  275. Mutex _directPaths_m;
  276. Mutex _backgroundTasksLock;
  277. uint64_t _now;
  278. uint64_t _lastPingCheck;
  279. uint64_t _lastHousekeepingRun;
  280. volatile uint64_t _prngState[2];
  281. bool _online;
  282. };
  283. } // namespace ZeroTier
  284. #endif