Node.hpp 10 KB

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