Node.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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. #include "Hashtable.hpp"
  44. #undef TRACE
  45. #ifdef ZT_TRACE
  46. #define TRACE(f,...) RR->node->postTrace(__FILE__,__LINE__,f,##__VA_ARGS__)
  47. #else
  48. #define TRACE(f,...) {}
  49. #endif
  50. // Bit mask for "expecting reply" hash
  51. #define ZT_EXPECTING_REPLIES_BUCKET_MASK1 255
  52. #define ZT_EXPECTING_REPLIES_BUCKET_MASK2 31
  53. namespace ZeroTier {
  54. class World;
  55. /**
  56. * Implementation of Node object as defined in CAPI
  57. *
  58. * The pointer returned by ZT_Node_new() is an instance of this class.
  59. */
  60. class Node : public NetworkController::Sender
  61. {
  62. public:
  63. Node(void *uptr,void *tptr,const struct ZT_Node_Callbacks *callbacks,uint64_t now);
  64. virtual ~Node();
  65. // Get rid of alignment warnings on 32-bit Windows and possibly improve performance
  66. #ifdef __WINDOWS__
  67. void * operator new(size_t i) { return _mm_malloc(i,16); }
  68. void operator delete(void* p) { _mm_free(p); }
  69. #endif
  70. // Public API Functions ----------------------------------------------------
  71. ZT_ResultCode processStateUpdate(
  72. void *tptr,
  73. ZT_StateObjectType type,
  74. uint64_t id,
  75. const void *data,
  76. unsigned int len);
  77. ZT_ResultCode processWirePacket(
  78. void *tptr,
  79. uint64_t now,
  80. const struct sockaddr_storage *localAddress,
  81. const struct sockaddr_storage *remoteAddress,
  82. const void *packetData,
  83. unsigned int packetLength,
  84. volatile uint64_t *nextBackgroundTaskDeadline);
  85. ZT_ResultCode processVirtualNetworkFrame(
  86. void *tptr,
  87. uint64_t now,
  88. uint64_t nwid,
  89. uint64_t sourceMac,
  90. uint64_t destMac,
  91. unsigned int etherType,
  92. unsigned int vlanId,
  93. const void *frameData,
  94. unsigned int frameLength,
  95. volatile uint64_t *nextBackgroundTaskDeadline);
  96. ZT_ResultCode processBackgroundTasks(void *tptr,uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline);
  97. ZT_ResultCode join(uint64_t nwid,void *uptr,void *tptr);
  98. ZT_ResultCode leave(uint64_t nwid,void **uptr,void *tptr);
  99. ZT_ResultCode multicastSubscribe(void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi);
  100. ZT_ResultCode multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi);
  101. ZT_ResultCode orbit(void *tptr,uint64_t moonWorldId,uint64_t moonSeed);
  102. ZT_ResultCode deorbit(void *tptr,uint64_t moonWorldId);
  103. uint64_t address() const;
  104. void status(ZT_NodeStatus *status) const;
  105. ZT_PeerList *peers() const;
  106. ZT_VirtualNetworkConfig *networkConfig(uint64_t nwid) const;
  107. ZT_VirtualNetworkList *networks() const;
  108. void freeQueryResult(void *qr);
  109. int addLocalInterfaceAddress(const struct sockaddr_storage *addr);
  110. void clearLocalInterfaceAddresses();
  111. int sendUserMessage(void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len);
  112. void setNetconfMaster(void *networkControllerInstance);
  113. // Internal functions ------------------------------------------------------
  114. inline uint64_t now() const throw() { return _now; }
  115. inline bool putPacket(void *tPtr,const InetAddress &localAddress,const InetAddress &addr,const void *data,unsigned int len,unsigned int ttl = 0)
  116. {
  117. return (_cb.wirePacketSendFunction(
  118. reinterpret_cast<ZT_Node *>(this),
  119. _uPtr,
  120. tPtr,
  121. reinterpret_cast<const struct sockaddr_storage *>(&localAddress),
  122. reinterpret_cast<const struct sockaddr_storage *>(&addr),
  123. data,
  124. len,
  125. ttl) == 0);
  126. }
  127. 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)
  128. {
  129. _cb.virtualNetworkFrameFunction(
  130. reinterpret_cast<ZT_Node *>(this),
  131. _uPtr,
  132. tPtr,
  133. nwid,
  134. nuptr,
  135. source.toInt(),
  136. dest.toInt(),
  137. etherType,
  138. vlanId,
  139. data,
  140. len);
  141. }
  142. inline SharedPtr<Network> network(uint64_t nwid) const
  143. {
  144. Mutex::Lock _l(_networks_m);
  145. const SharedPtr<Network> *n = _networks.get(nwid);
  146. if (n)
  147. return *n;
  148. return SharedPtr<Network>();
  149. }
  150. inline bool belongsToNetwork(uint64_t nwid) const
  151. {
  152. Mutex::Lock _l(_networks_m);
  153. return _networks.contains(nwid);
  154. }
  155. inline std::vector< SharedPtr<Network> > allNetworks() const
  156. {
  157. std::vector< SharedPtr<Network> > nw;
  158. Mutex::Lock _l(_networks_m);
  159. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(*const_cast< Hashtable< uint64_t,SharedPtr<Network> > * >(&_networks));
  160. uint64_t *k = (uint64_t *)0;
  161. SharedPtr<Network> *v = (SharedPtr<Network> *)0;
  162. while (i.next(k,v))
  163. nw.push_back(*v);
  164. return nw;
  165. }
  166. inline std::vector<InetAddress> directPaths() const
  167. {
  168. Mutex::Lock _l(_directPaths_m);
  169. return _directPaths;
  170. }
  171. 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); }
  172. 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); }
  173. inline bool online() const throw() { return _online; }
  174. inline int stateObjectGet(void *const tPtr,ZT_StateObjectType type,const uint64_t id[2],void *const data,const unsigned int maxlen) { return _cb.stateGetFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,type,id,data,maxlen); }
  175. inline void stateObjectPut(void *const tPtr,ZT_StateObjectType type,const uint64_t id[2],const void *const data,const unsigned int len) { _cb.statePutFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,type,id,data,(int)len); }
  176. inline void stateObjectDelete(void *const tPtr,ZT_StateObjectType type,const uint64_t id[2]) { _cb.statePutFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,type,id,(const void *)0,-1); }
  177. #ifdef ZT_TRACE
  178. void postTrace(const char *module,unsigned int line,const char *fmt,...);
  179. #endif
  180. bool shouldUsePathForZeroTierTraffic(void *tPtr,const Address &ztaddr,const InetAddress &localAddress,const InetAddress &remoteAddress);
  181. 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 ); }
  182. uint64_t prng();
  183. void setTrustedPaths(const struct sockaddr_storage *networks,const uint64_t *ids,unsigned int count);
  184. World planet() const;
  185. std::vector<World> moons() const;
  186. inline const Identity &identity() const { return _RR.identity; }
  187. /**
  188. * Register that we are expecting a reply to a packet ID
  189. *
  190. * This only uses the most significant bits of the packet ID, both to save space
  191. * and to avoid using the higher bits that can be modified during armor() to
  192. * mask against the packet send counter used for QoS detection.
  193. *
  194. * @param packetId Packet ID to expect reply to
  195. */
  196. inline void expectReplyTo(const uint64_t packetId)
  197. {
  198. const unsigned long pid2 = (unsigned long)(packetId >> 32);
  199. const unsigned long bucket = (unsigned long)(pid2 & ZT_EXPECTING_REPLIES_BUCKET_MASK1);
  200. _expectingRepliesTo[bucket][_expectingRepliesToBucketPtr[bucket]++ & ZT_EXPECTING_REPLIES_BUCKET_MASK2] = (uint32_t)pid2;
  201. }
  202. /**
  203. * Check whether a given packet ID is something we are expecting a reply to
  204. *
  205. * This only uses the most significant bits of the packet ID, both to save space
  206. * and to avoid using the higher bits that can be modified during armor() to
  207. * mask against the packet send counter used for QoS detection.
  208. *
  209. * @param packetId Packet ID to check
  210. * @return True if we're expecting a reply
  211. */
  212. inline bool expectingReplyTo(const uint64_t packetId) const
  213. {
  214. const uint32_t pid2 = (uint32_t)(packetId >> 32);
  215. const unsigned long bucket = (unsigned long)(pid2 & ZT_EXPECTING_REPLIES_BUCKET_MASK1);
  216. for(unsigned long i=0;i<=ZT_EXPECTING_REPLIES_BUCKET_MASK2;++i) {
  217. if (_expectingRepliesTo[bucket][i] == pid2)
  218. return true;
  219. }
  220. return false;
  221. }
  222. /**
  223. * Check whether we should do potentially expensive identity verification (rate limit)
  224. *
  225. * @param now Current time
  226. * @param from Source address of packet
  227. * @return True if within rate limits
  228. */
  229. inline bool rateGateIdentityVerification(const uint64_t now,const InetAddress &from)
  230. {
  231. unsigned long iph = from.rateGateHash();
  232. if ((now - _lastIdentityVerification[iph]) >= ZT_IDENTITY_VALIDATION_SOURCE_RATE_LIMIT) {
  233. _lastIdentityVerification[iph] = now;
  234. return true;
  235. }
  236. return false;
  237. }
  238. virtual void ncSendConfig(uint64_t nwid,uint64_t requestPacketId,const Address &destination,const NetworkConfig &nc,bool sendLegacyFormatConfig);
  239. virtual void ncSendRevocation(const Address &destination,const Revocation &rev);
  240. virtual void ncSendError(uint64_t nwid,uint64_t requestPacketId,const Address &destination,NetworkController::ErrorCode errorCode);
  241. private:
  242. RuntimeEnvironment _RR;
  243. RuntimeEnvironment *RR;
  244. void *_uPtr; // _uptr (lower case) is reserved in Visual Studio :P
  245. ZT_Node_Callbacks _cb;
  246. // For tracking packet IDs to filter out OK/ERROR replies to packets we did not send
  247. uint8_t _expectingRepliesToBucketPtr[ZT_EXPECTING_REPLIES_BUCKET_MASK1 + 1];
  248. uint32_t _expectingRepliesTo[ZT_EXPECTING_REPLIES_BUCKET_MASK1 + 1][ZT_EXPECTING_REPLIES_BUCKET_MASK2 + 1];
  249. // Time of last identity verification indexed by InetAddress.rateGateHash() -- used in IncomingPacket::_doHELLO() via rateGateIdentityVerification()
  250. uint64_t _lastIdentityVerification[16384];
  251. Hashtable< uint64_t,SharedPtr<Network> > _networks;
  252. Mutex _networks_m;
  253. std::vector<InetAddress> _directPaths;
  254. Mutex _directPaths_m;
  255. Mutex _backgroundTasksLock;
  256. uint64_t _now;
  257. uint64_t _lastPingCheck;
  258. uint64_t _lastHousekeepingRun;
  259. volatile uint64_t _prngState[2];
  260. bool _online;
  261. };
  262. } // namespace ZeroTier
  263. #endif