Node.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. namespace ZeroTier {
  44. /**
  45. * Implementation of Node object as defined in CAPI
  46. *
  47. * The pointer returned by ZT_Node_new() is an instance of this class.
  48. */
  49. class Node : public NetworkController::Sender
  50. {
  51. public:
  52. Node(
  53. uint64_t now,
  54. void *uptr,
  55. ZT_DataStoreGetFunction dataStoreGetFunction,
  56. ZT_DataStorePutFunction dataStorePutFunction,
  57. ZT_WirePacketSendFunction wirePacketSendFunction,
  58. ZT_VirtualNetworkFrameFunction virtualNetworkFrameFunction,
  59. ZT_VirtualNetworkConfigFunction virtualNetworkConfigFunction,
  60. ZT_PathCheckFunction pathCheckFunction,
  61. ZT_EventCallback eventCallback);
  62. virtual ~Node();
  63. // Public API Functions ----------------------------------------------------
  64. ZT_ResultCode processWirePacket(
  65. uint64_t now,
  66. const struct sockaddr_storage *localAddress,
  67. const struct sockaddr_storage *remoteAddress,
  68. const void *packetData,
  69. unsigned int packetLength,
  70. volatile uint64_t *nextBackgroundTaskDeadline);
  71. ZT_ResultCode processVirtualNetworkFrame(
  72. uint64_t now,
  73. uint64_t nwid,
  74. uint64_t sourceMac,
  75. uint64_t destMac,
  76. unsigned int etherType,
  77. unsigned int vlanId,
  78. const void *frameData,
  79. unsigned int frameLength,
  80. volatile uint64_t *nextBackgroundTaskDeadline);
  81. ZT_ResultCode processBackgroundTasks(uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline);
  82. ZT_ResultCode setRelayPolicy(enum ZT_RelayPolicy rp);
  83. ZT_ResultCode join(uint64_t nwid,void *uptr);
  84. ZT_ResultCode leave(uint64_t nwid,void **uptr);
  85. ZT_ResultCode multicastSubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi);
  86. ZT_ResultCode multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi);
  87. uint64_t address() const;
  88. void status(ZT_NodeStatus *status) const;
  89. ZT_PeerList *peers() const;
  90. ZT_VirtualNetworkConfig *networkConfig(uint64_t nwid) const;
  91. ZT_VirtualNetworkList *networks() const;
  92. void freeQueryResult(void *qr);
  93. int addLocalInterfaceAddress(const struct sockaddr_storage *addr);
  94. void clearLocalInterfaceAddresses();
  95. void setNetconfMaster(void *networkControllerInstance);
  96. ZT_ResultCode circuitTestBegin(ZT_CircuitTest *test,void (*reportCallback)(ZT_Node *,ZT_CircuitTest *,const ZT_CircuitTestReport *));
  97. void circuitTestEnd(ZT_CircuitTest *test);
  98. ZT_ResultCode clusterInit(
  99. unsigned int myId,
  100. const struct sockaddr_storage *zeroTierPhysicalEndpoints,
  101. unsigned int numZeroTierPhysicalEndpoints,
  102. int x,
  103. int y,
  104. int z,
  105. void (*sendFunction)(void *,unsigned int,const void *,unsigned int),
  106. void *sendFunctionArg,
  107. int (*addressToLocationFunction)(void *,const struct sockaddr_storage *,int *,int *,int *),
  108. void *addressToLocationFunctionArg);
  109. ZT_ResultCode clusterAddMember(unsigned int memberId);
  110. void clusterRemoveMember(unsigned int memberId);
  111. void clusterHandleIncomingMessage(const void *msg,unsigned int len);
  112. void clusterStatus(ZT_ClusterStatus *cs);
  113. // Internal functions ------------------------------------------------------
  114. /**
  115. * @return Time as of last call to run()
  116. */
  117. inline uint64_t now() const throw() { return _now; }
  118. /**
  119. * Enqueue a ZeroTier message to be sent
  120. *
  121. * @param localAddress Local address
  122. * @param addr Destination address
  123. * @param data Packet data
  124. * @param len Packet length
  125. * @param ttl Desired TTL (default: 0 for unchanged/default TTL)
  126. * @return True if packet appears to have been sent
  127. */
  128. inline bool putPacket(const InetAddress &localAddress,const InetAddress &addr,const void *data,unsigned int len,unsigned int ttl = 0)
  129. {
  130. return (_wirePacketSendFunction(
  131. reinterpret_cast<ZT_Node *>(this),
  132. _uPtr,
  133. reinterpret_cast<const struct sockaddr_storage *>(&localAddress),
  134. reinterpret_cast<const struct sockaddr_storage *>(&addr),
  135. data,
  136. len,
  137. ttl) == 0);
  138. }
  139. /**
  140. * Enqueue a frame to be injected into a tap device (port)
  141. *
  142. * @param nwid Network ID
  143. * @param nuptr Network user ptr
  144. * @param source Source MAC
  145. * @param dest Destination MAC
  146. * @param etherType 16-bit ethernet type
  147. * @param vlanId VLAN ID or 0 if none
  148. * @param data Frame data
  149. * @param len Frame length
  150. */
  151. 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)
  152. {
  153. _virtualNetworkFrameFunction(
  154. reinterpret_cast<ZT_Node *>(this),
  155. _uPtr,
  156. nwid,
  157. nuptr,
  158. source.toInt(),
  159. dest.toInt(),
  160. etherType,
  161. vlanId,
  162. data,
  163. len);
  164. }
  165. /**
  166. * @param localAddress Local address
  167. * @param remoteAddress Remote address
  168. * @return True if path should be used
  169. */
  170. bool shouldUsePathForZeroTierTraffic(const InetAddress &localAddress,const InetAddress &remoteAddress);
  171. inline SharedPtr<Network> network(uint64_t nwid) const
  172. {
  173. Mutex::Lock _l(_networks_m);
  174. return _network(nwid);
  175. }
  176. inline bool belongsToNetwork(uint64_t nwid) const
  177. {
  178. Mutex::Lock _l(_networks_m);
  179. for(std::vector< std::pair< uint64_t, SharedPtr<Network> > >::const_iterator i=_networks.begin();i!=_networks.end();++i) {
  180. if (i->first == nwid)
  181. return true;
  182. }
  183. return false;
  184. }
  185. inline std::vector< SharedPtr<Network> > allNetworks() const
  186. {
  187. std::vector< SharedPtr<Network> > nw;
  188. Mutex::Lock _l(_networks_m);
  189. nw.reserve(_networks.size());
  190. for(std::vector< std::pair< uint64_t, SharedPtr<Network> > >::const_iterator i=_networks.begin();i!=_networks.end();++i)
  191. nw.push_back(i->second);
  192. return nw;
  193. }
  194. /**
  195. * @return Potential direct paths to me a.k.a. local interface addresses
  196. */
  197. inline std::vector<InetAddress> directPaths() const
  198. {
  199. Mutex::Lock _l(_directPaths_m);
  200. return _directPaths;
  201. }
  202. inline bool dataStorePut(const char *name,const void *data,unsigned int len,bool secure) { return (_dataStorePutFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,name,data,len,(int)secure) == 0); }
  203. inline bool dataStorePut(const char *name,const std::string &data,bool secure) { return dataStorePut(name,(const void *)data.data(),(unsigned int)data.length(),secure); }
  204. inline void dataStoreDelete(const char *name) { _dataStorePutFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,name,(const void *)0,0,0); }
  205. std::string dataStoreGet(const char *name);
  206. /**
  207. * Post an event to the external user
  208. *
  209. * @param ev Event type
  210. * @param md Meta-data (default: NULL/none)
  211. */
  212. inline void postEvent(ZT_Event ev,const void *md = (const void *)0) { _eventCallback(reinterpret_cast<ZT_Node *>(this),_uPtr,ev,md); }
  213. /**
  214. * Update virtual network port configuration
  215. *
  216. * @param nwid Network ID
  217. * @param nuptr Network user ptr
  218. * @param op Configuration operation
  219. * @param nc Network configuration
  220. */
  221. inline int configureVirtualNetworkPort(uint64_t nwid,void **nuptr,ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nc) { return _virtualNetworkConfigFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,nwid,nuptr,op,nc); }
  222. inline bool online() const throw() { return _online; }
  223. inline ZT_RelayPolicy relayPolicy() const { return _relayPolicy; }
  224. #ifdef ZT_TRACE
  225. void postTrace(const char *module,unsigned int line,const char *fmt,...);
  226. #endif
  227. uint64_t prng();
  228. void postCircuitTestReport(const ZT_CircuitTestReport *report);
  229. void setTrustedPaths(const struct sockaddr_storage *networks,const uint64_t *ids,unsigned int count);
  230. /**
  231. * Register that we are expecting a reply to a packet ID
  232. *
  233. * @param packetId Packet ID to expect reply to
  234. */
  235. inline void expectReplyTo(const uint64_t packetId)
  236. {
  237. const unsigned long bucket = (unsigned long)(packetId & ZT_EXPECTING_REPLIES_BUCKET_MASK1);
  238. _expectingRepliesTo[bucket][_expectingRepliesToBucketPtr[bucket]++ & ZT_EXPECTING_REPLIES_BUCKET_MASK2] = packetId;
  239. }
  240. /**
  241. * Check whether a given packet ID is something we are expecting a reply to
  242. *
  243. * @param packetId Packet ID to check
  244. * @return True if we're expecting a reply
  245. */
  246. inline bool expectingReplyTo(const uint64_t packetId) const
  247. {
  248. const unsigned long bucket = (unsigned long)(packetId & ZT_EXPECTING_REPLIES_BUCKET_MASK1);
  249. for(unsigned long i=0;i<=ZT_EXPECTING_REPLIES_BUCKET_MASK2;++i) {
  250. if (_expectingRepliesTo[bucket][i] == packetId)
  251. return true;
  252. }
  253. return false;
  254. }
  255. virtual void ncSendConfig(uint64_t nwid,uint64_t requestPacketId,const Address &destination,const NetworkConfig &nc,bool sendLegacyFormatConfig);
  256. virtual void ncSendError(uint64_t nwid,uint64_t requestPacketId,const Address &destination,NetworkController::ErrorCode errorCode);
  257. private:
  258. inline SharedPtr<Network> _network(uint64_t nwid) const
  259. {
  260. // assumes _networks_m is locked
  261. for(std::vector< std::pair< uint64_t, SharedPtr<Network> > >::const_iterator i=_networks.begin();i!=_networks.end();++i) {
  262. if (i->first == nwid)
  263. return i->second;
  264. }
  265. return SharedPtr<Network>();
  266. }
  267. RuntimeEnvironment _RR;
  268. RuntimeEnvironment *RR;
  269. void *_uPtr; // _uptr (lower case) is reserved in Visual Studio :P
  270. uint8_t _expectingRepliesToBucketPtr[ZT_EXPECTING_REPLIES_BUCKET_MASK1 + 1];
  271. uint64_t _expectingRepliesTo[ZT_EXPECTING_REPLIES_BUCKET_MASK1 + 1][ZT_EXPECTING_REPLIES_BUCKET_MASK2 + 1];
  272. ZT_DataStoreGetFunction _dataStoreGetFunction;
  273. ZT_DataStorePutFunction _dataStorePutFunction;
  274. ZT_WirePacketSendFunction _wirePacketSendFunction;
  275. ZT_VirtualNetworkFrameFunction _virtualNetworkFrameFunction;
  276. ZT_VirtualNetworkConfigFunction _virtualNetworkConfigFunction;
  277. ZT_PathCheckFunction _pathCheckFunction;
  278. ZT_EventCallback _eventCallback;
  279. std::vector< std::pair< uint64_t, SharedPtr<Network> > > _networks;
  280. Mutex _networks_m;
  281. std::vector< ZT_CircuitTest * > _circuitTests;
  282. Mutex _circuitTests_m;
  283. std::vector<InetAddress> _directPaths;
  284. Mutex _directPaths_m;
  285. Mutex _backgroundTasksLock;
  286. unsigned int _prngStreamPtr;
  287. Salsa20 _prng;
  288. uint64_t _prngStream[16]; // repeatedly encrypted with _prng to yield a high-quality non-crypto PRNG stream
  289. uint64_t _now;
  290. uint64_t _lastPingCheck;
  291. uint64_t _lastHousekeepingRun;
  292. ZT_RelayPolicy _relayPolicy;
  293. bool _online;
  294. };
  295. } // namespace ZeroTier
  296. #endif