Node.hpp 11 KB

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