Node.hpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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. #undef TRACE
  34. #ifdef ZT_TRACE
  35. #define TRACE(f,...) RR->node->postTrace(__FILE__,__LINE__,f,##__VA_ARGS__)
  36. #else
  37. #define TRACE(f,...) {}
  38. #endif
  39. namespace ZeroTier {
  40. /**
  41. * Implementation of Node object as defined in CAPI
  42. *
  43. * The pointer returned by ZT_Node_new() is an instance of this class.
  44. */
  45. class Node
  46. {
  47. public:
  48. Node(
  49. uint64_t now,
  50. void *uptr,
  51. ZT_DataStoreGetFunction dataStoreGetFunction,
  52. ZT_DataStorePutFunction dataStorePutFunction,
  53. ZT_WirePacketSendFunction wirePacketSendFunction,
  54. ZT_VirtualNetworkFrameFunction virtualNetworkFrameFunction,
  55. ZT_VirtualNetworkConfigFunction virtualNetworkConfigFunction,
  56. ZT_PathCheckFunction pathCheckFunction,
  57. ZT_EventCallback eventCallback);
  58. ~Node();
  59. // Public API Functions ----------------------------------------------------
  60. ZT_ResultCode processWirePacket(
  61. uint64_t now,
  62. const struct sockaddr_storage *localAddress,
  63. const struct sockaddr_storage *remoteAddress,
  64. const void *packetData,
  65. unsigned int packetLength,
  66. volatile uint64_t *nextBackgroundTaskDeadline);
  67. ZT_ResultCode processVirtualNetworkFrame(
  68. uint64_t now,
  69. uint64_t nwid,
  70. uint64_t sourceMac,
  71. uint64_t destMac,
  72. unsigned int etherType,
  73. unsigned int vlanId,
  74. const void *frameData,
  75. unsigned int frameLength,
  76. volatile uint64_t *nextBackgroundTaskDeadline);
  77. ZT_ResultCode processBackgroundTasks(uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline);
  78. ZT_ResultCode join(uint64_t nwid,void *uptr);
  79. ZT_ResultCode leave(uint64_t nwid,void **uptr);
  80. ZT_ResultCode multicastSubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi);
  81. ZT_ResultCode multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi);
  82. uint64_t address() const;
  83. void status(ZT_NodeStatus *status) const;
  84. ZT_PeerList *peers() const;
  85. ZT_VirtualNetworkConfig *networkConfig(uint64_t nwid) const;
  86. ZT_VirtualNetworkList *networks() const;
  87. void freeQueryResult(void *qr);
  88. int addLocalInterfaceAddress(const struct sockaddr_storage *addr);
  89. void clearLocalInterfaceAddresses();
  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. void backgroundThreadMain();
  109. // Internal functions ------------------------------------------------------
  110. /**
  111. * Convenience threadMain() for easy background thread launch
  112. *
  113. * This allows background threads to be launched with Thread::start
  114. * that will run against this node.
  115. */
  116. inline void threadMain() throw() { this->backgroundThreadMain(); }
  117. /**
  118. * @return Time as of last call to run()
  119. */
  120. inline uint64_t now() const throw() { return _now; }
  121. /**
  122. * Enqueue a ZeroTier message to be sent
  123. *
  124. * @param localAddress Local address
  125. * @param addr Destination address
  126. * @param data Packet data
  127. * @param len Packet length
  128. * @param ttl Desired TTL (default: 0 for unchanged/default TTL)
  129. * @return True if packet appears to have been sent
  130. */
  131. inline bool putPacket(const InetAddress &localAddress,const InetAddress &addr,const void *data,unsigned int len,unsigned int ttl = 0)
  132. {
  133. return (_wirePacketSendFunction(
  134. reinterpret_cast<ZT_Node *>(this),
  135. _uPtr,
  136. reinterpret_cast<const struct sockaddr_storage *>(&localAddress),
  137. reinterpret_cast<const struct sockaddr_storage *>(&addr),
  138. data,
  139. len,
  140. ttl) == 0);
  141. }
  142. /**
  143. * Enqueue a frame to be injected into a tap device (port)
  144. *
  145. * @param nwid Network ID
  146. * @param nuptr Network user ptr
  147. * @param source Source MAC
  148. * @param dest Destination MAC
  149. * @param etherType 16-bit ethernet type
  150. * @param vlanId VLAN ID or 0 if none
  151. * @param data Frame data
  152. * @param len Frame length
  153. */
  154. 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)
  155. {
  156. _virtualNetworkFrameFunction(
  157. reinterpret_cast<ZT_Node *>(this),
  158. _uPtr,
  159. nwid,
  160. nuptr,
  161. source.toInt(),
  162. dest.toInt(),
  163. etherType,
  164. vlanId,
  165. data,
  166. len);
  167. }
  168. /**
  169. * @param localAddress Local address
  170. * @param remoteAddress Remote address
  171. * @return True if path should be used
  172. */
  173. bool shouldUsePathForZeroTierTraffic(const InetAddress &localAddress,const InetAddress &remoteAddress);
  174. inline SharedPtr<Network> network(uint64_t nwid) const
  175. {
  176. Mutex::Lock _l(_networks_m);
  177. return _network(nwid);
  178. }
  179. inline bool belongsToNetwork(uint64_t nwid) const
  180. {
  181. Mutex::Lock _l(_networks_m);
  182. for(std::vector< std::pair< uint64_t, SharedPtr<Network> > >::const_iterator i=_networks.begin();i!=_networks.end();++i) {
  183. if (i->first == nwid)
  184. return true;
  185. }
  186. return false;
  187. }
  188. inline std::vector< SharedPtr<Network> > allNetworks() const
  189. {
  190. std::vector< SharedPtr<Network> > nw;
  191. Mutex::Lock _l(_networks_m);
  192. nw.reserve(_networks.size());
  193. for(std::vector< std::pair< uint64_t, SharedPtr<Network> > >::const_iterator i=_networks.begin();i!=_networks.end();++i)
  194. nw.push_back(i->second);
  195. return nw;
  196. }
  197. /**
  198. * @return Potential direct paths to me a.k.a. local interface addresses
  199. */
  200. inline std::vector<InetAddress> directPaths() const
  201. {
  202. Mutex::Lock _l(_directPaths_m);
  203. return _directPaths;
  204. }
  205. 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); }
  206. inline bool dataStorePut(const char *name,const std::string &data,bool secure) { return dataStorePut(name,(const void *)data.data(),(unsigned int)data.length(),secure); }
  207. inline void dataStoreDelete(const char *name) { _dataStorePutFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,name,(const void *)0,0,0); }
  208. std::string dataStoreGet(const char *name);
  209. /**
  210. * Post an event to the external user
  211. *
  212. * @param ev Event type
  213. * @param md Meta-data (default: NULL/none)
  214. */
  215. inline void postEvent(ZT_Event ev,const void *md = (const void *)0) { _eventCallback(reinterpret_cast<ZT_Node *>(this),_uPtr,ev,md); }
  216. /**
  217. * Update virtual network port configuration
  218. *
  219. * @param nwid Network ID
  220. * @param nuptr Network user ptr
  221. * @param op Configuration operation
  222. * @param nc Network configuration
  223. */
  224. 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); }
  225. /**
  226. * @return True if we appear to be online
  227. */
  228. inline bool online() const throw() { return _online; }
  229. #ifdef ZT_TRACE
  230. void postTrace(const char *module,unsigned int line,const char *fmt,...);
  231. #endif
  232. /**
  233. * @return Next 64-bit random number (not for cryptographic use)
  234. */
  235. uint64_t prng();
  236. /**
  237. * Post a circuit test report to any listeners for a given test ID
  238. *
  239. * @param report Report (includes test ID)
  240. */
  241. void postCircuitTestReport(const ZT_CircuitTestReport *report);
  242. private:
  243. inline SharedPtr<Network> _network(uint64_t nwid) const
  244. {
  245. // assumes _networks_m is locked
  246. for(std::vector< std::pair< uint64_t, SharedPtr<Network> > >::const_iterator i=_networks.begin();i!=_networks.end();++i) {
  247. if (i->first == nwid)
  248. return i->second;
  249. }
  250. return SharedPtr<Network>();
  251. }
  252. RuntimeEnvironment _RR;
  253. RuntimeEnvironment *RR;
  254. void *_uPtr; // _uptr (lower case) is reserved in Visual Studio :P
  255. ZT_DataStoreGetFunction _dataStoreGetFunction;
  256. ZT_DataStorePutFunction _dataStorePutFunction;
  257. ZT_WirePacketSendFunction _wirePacketSendFunction;
  258. ZT_VirtualNetworkFrameFunction _virtualNetworkFrameFunction;
  259. ZT_VirtualNetworkConfigFunction _virtualNetworkConfigFunction;
  260. ZT_PathCheckFunction _pathCheckFunction;
  261. ZT_EventCallback _eventCallback;
  262. std::vector< std::pair< uint64_t, SharedPtr<Network> > > _networks;
  263. Mutex _networks_m;
  264. std::vector< ZT_CircuitTest * > _circuitTests;
  265. Mutex _circuitTests_m;
  266. std::vector<InetAddress> _directPaths;
  267. Mutex _directPaths_m;
  268. Mutex _backgroundTasksLock;
  269. unsigned int _prngStreamPtr;
  270. Salsa20 _prng;
  271. uint64_t _prngStream[16]; // repeatedly encrypted with _prng to yield a high-quality non-crypto PRNG stream
  272. uint64_t _now;
  273. uint64_t _lastPingCheck;
  274. uint64_t _lastHousekeepingRun;
  275. bool _online;
  276. };
  277. } // namespace ZeroTier
  278. #endif