Node.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2024-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #ifndef ZT_NODE_HPP
  14. #define ZT_NODE_HPP
  15. #include <cstdio>
  16. #include <cstdlib>
  17. #include <cstring>
  18. #include <map>
  19. #include <vector>
  20. #include "Constants.hpp"
  21. #include "RuntimeEnvironment.hpp"
  22. #include "InetAddress.hpp"
  23. #include "Mutex.hpp"
  24. #include "MAC.hpp"
  25. #include "Network.hpp"
  26. #include "Path.hpp"
  27. #include "Salsa20.hpp"
  28. #include "NetworkController.hpp"
  29. #include "Hashtable.hpp"
  30. // Bit mask for "expecting reply" hash
  31. #define ZT_EXPECTING_REPLIES_BUCKET_MASK1 255
  32. #define ZT_EXPECTING_REPLIES_BUCKET_MASK2 31
  33. namespace ZeroTier {
  34. class Locator;
  35. /**
  36. * Implementation of Node object as defined in CAPI
  37. *
  38. * The pointer returned by ZT_Node_new() is an instance of this class.
  39. */
  40. class Node : public NetworkController::Sender
  41. {
  42. public:
  43. Node(void *uPtr,void *tPtr,const struct ZT_Node_Callbacks *callbacks,int64_t now);
  44. virtual ~Node();
  45. /**
  46. * Perform any operations that should be done prior to deleting a Node
  47. *
  48. * This is technically optional but recommended.
  49. *
  50. * @param tPtr Thread pointer to pass through to callbacks
  51. */
  52. void shutdown(void *tPtr);
  53. // Get rid of alignment warnings on 32-bit Windows and possibly improve performance
  54. #ifdef __WINDOWS__
  55. void * operator new(size_t i) { return _mm_malloc(i,16); }
  56. void operator delete(void* p) { _mm_free(p); }
  57. #endif
  58. // Public API Functions ----------------------------------------------------
  59. ZT_ResultCode processWirePacket(
  60. void *tptr,
  61. int64_t now,
  62. int64_t localSocket,
  63. const struct sockaddr_storage *remoteAddress,
  64. const void *packetData,
  65. unsigned int packetLength,
  66. volatile int64_t *nextBackgroundTaskDeadline);
  67. ZT_ResultCode processVirtualNetworkFrame(
  68. void *tptr,
  69. int64_t now,
  70. uint64_t nwid,
  71. uint64_t sourceMac,
  72. uint64_t destMac,
  73. unsigned int etherType,
  74. unsigned int vlanId,
  75. const void *frameData,
  76. unsigned int frameLength,
  77. volatile int64_t *nextBackgroundTaskDeadline);
  78. ZT_ResultCode processBackgroundTasks(void *tPtr, int64_t now, volatile int64_t *nextBackgroundTaskDeadline);
  79. ZT_ResultCode join(uint64_t nwid,void *uptr,void *tptr);
  80. ZT_ResultCode leave(uint64_t nwid,void **uptr,void *tptr);
  81. ZT_ResultCode multicastSubscribe(void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi);
  82. ZT_ResultCode multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi);
  83. ZT_ResultCode addRoot(void *tptr,const ZT_Identity *identity,const sockaddr_storage *bootstrap);
  84. ZT_ResultCode removeRoot(void *tptr,const ZT_Identity *identity);
  85. uint64_t address() const;
  86. void status(ZT_NodeStatus *status) const;
  87. ZT_PeerList *peers() const;
  88. ZT_VirtualNetworkConfig *networkConfig(uint64_t nwid) const;
  89. ZT_VirtualNetworkList *networks() const;
  90. void setNetworkUserPtr(uint64_t nwid,void *ptr);
  91. void freeQueryResult(void *qr);
  92. void setInterfaceAddresses(const ZT_InterfaceAddress *addrs,unsigned int addrCount);
  93. int sendUserMessage(void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len);
  94. void setController(void *networkControllerInstance);
  95. // Internal functions ------------------------------------------------------
  96. /**
  97. * @return Most recent time value supplied to core via API
  98. */
  99. ZT_ALWAYS_INLINE int64_t now() const { return _now; }
  100. /**
  101. * Send packet to to the physical wire via callback
  102. *
  103. * @param tPtr Thread pointer
  104. * @param localSocket Local socket or -1 to use all/any
  105. * @param addr Destination address
  106. * @param data Data to send
  107. * @param len Length in bytes
  108. * @param ttl TTL or 0 for default/max
  109. * @return True if send appears successful
  110. */
  111. ZT_ALWAYS_INLINE bool putPacket(void *tPtr,const int64_t localSocket,const InetAddress &addr,const void *data,unsigned int len,unsigned int ttl = 0)
  112. {
  113. return (_cb.wirePacketSendFunction(
  114. reinterpret_cast<ZT_Node *>(this),
  115. _uPtr,
  116. tPtr,
  117. localSocket,
  118. reinterpret_cast<const struct sockaddr_storage *>(&addr),
  119. data,
  120. len,
  121. ttl) == 0);
  122. }
  123. /**
  124. * Inject frame into virtual Ethernet tap
  125. *
  126. * @param tPtr Thread pointer
  127. * @param nwid Network ID
  128. * @param nuptr Network-associated user pointer
  129. * @param source Source MAC address
  130. * @param dest Destination MAC address
  131. * @param etherType 16-bit Ethernet type
  132. * @param vlanId Ethernet VLAN ID (currently unused)
  133. * @param data Ethernet frame data
  134. * @param len Ethernet frame length in bytes
  135. */
  136. ZT_ALWAYS_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)
  137. {
  138. _cb.virtualNetworkFrameFunction(
  139. reinterpret_cast<ZT_Node *>(this),
  140. _uPtr,
  141. tPtr,
  142. nwid,
  143. nuptr,
  144. source.toInt(),
  145. dest.toInt(),
  146. etherType,
  147. vlanId,
  148. data,
  149. len);
  150. }
  151. /**
  152. * @param nwid Network ID
  153. * @return Network associated with ID
  154. */
  155. ZT_ALWAYS_INLINE SharedPtr<Network> network(uint64_t nwid) const
  156. {
  157. RWMutex::RLock l(_networks_m);
  158. return _networks[(unsigned long)((nwid + (nwid >> 32U)) & _networksMask)];
  159. }
  160. /**
  161. * @return Known local interface addresses for this node
  162. */
  163. ZT_ALWAYS_INLINE std::vector<ZT_InterfaceAddress> localInterfaceAddresses() const
  164. {
  165. Mutex::Lock _l(_localInterfaceAddresses_m);
  166. return _localInterfaceAddresses;
  167. }
  168. /**
  169. * Post an event via external callback
  170. *
  171. * @param tPtr Thread pointer
  172. * @param ev Event object
  173. * @param md Event data or NULL if none
  174. */
  175. ZT_ALWAYS_INLINE void postEvent(void *tPtr,ZT_Event ev,const void *md = (const void *)0)
  176. {
  177. _cb.eventCallback(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,ev,md);
  178. }
  179. /**
  180. * Post network port configuration via external callback
  181. *
  182. * @param tPtr Thread pointer
  183. * @param nwid Network ID
  184. * @param nuptr Network-associated user pointer
  185. * @param op Config operation or event type
  186. * @param nc Network config info
  187. */
  188. ZT_ALWAYS_INLINE void configureVirtualNetworkPort(void *tPtr,uint64_t nwid,void **nuptr,ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nc)
  189. {
  190. _cb.virtualNetworkConfigFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,nwid,nuptr,op,nc);
  191. }
  192. /**
  193. * @return True if node appears online
  194. */
  195. ZT_ALWAYS_INLINE bool online() const { return _online; }
  196. /**
  197. * Get a state object
  198. *
  199. * @param tPtr Thread pointer
  200. * @param type Object type to get
  201. * @param id Object ID
  202. * @return Vector containing data or empty vector if not found or empty
  203. */
  204. std::vector<uint8_t> stateObjectGet(void *const tPtr,ZT_StateObjectType type,const uint64_t id[2]);
  205. /**
  206. * Store a state object
  207. *
  208. * @param tPtr Thread pointer
  209. * @param type Object type to get
  210. * @param id Object ID
  211. * @param data Data to store
  212. * @param len Length of data
  213. */
  214. ZT_ALWAYS_INLINE void stateObjectPut(void *const tPtr,ZT_StateObjectType type,const uint64_t id[2],const void *const data,const unsigned int len)
  215. {
  216. if (_cb.statePutFunction)
  217. _cb.statePutFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,type,id,data,(int)len);
  218. }
  219. /**
  220. * Delete a state object
  221. *
  222. * @param tPtr Thread pointer
  223. * @param type Object type to delete
  224. * @param id Object ID
  225. */
  226. ZT_ALWAYS_INLINE void stateObjectDelete(void *const tPtr,ZT_StateObjectType type,const uint64_t id[2])
  227. {
  228. if (_cb.statePutFunction)
  229. _cb.statePutFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,type,id,(const void *)0,-1);
  230. }
  231. /**
  232. * Check whether a path should be used for ZeroTier traffic
  233. *
  234. * This performs internal checks and also calls out to an external callback if one is defined.
  235. *
  236. * @param tPtr Thread pointer
  237. * @param id Identity of peer
  238. * @param localSocket Local socket or -1 if unknown
  239. * @param remoteAddress Remote address
  240. * @return True if path should be used
  241. */
  242. bool shouldUsePathForZeroTierTraffic(void *tPtr,const Identity &id,int64_t localSocket,const InetAddress &remoteAddress);
  243. /**
  244. * Query callback for a physical address for a peer
  245. *
  246. * @param tPtr Thread pointer
  247. * @param id Full identity of ZeroTier node
  248. * @param family Desired address family or -1 for any
  249. * @param addr Buffer to store address (result paramter)
  250. * @return True if addr was filled with something
  251. */
  252. bool externalPathLookup(void *tPtr,const Identity &id,int family,InetAddress &addr);
  253. /**
  254. * Set physical path configuration
  255. *
  256. * @param pathNetwork Physical path network/netmask bits (CIDR notation)
  257. * @param pathConfig Path configuration
  258. * @return Return to pass through to external API
  259. */
  260. ZT_ResultCode setPhysicalPathConfiguration(const struct sockaddr_storage *pathNetwork,const ZT_PhysicalPathConfiguration *pathConfig);
  261. /**
  262. * @return This node's identity
  263. */
  264. ZT_ALWAYS_INLINE const Identity &identity() const { return _RR.identity; }
  265. /**
  266. * Register that we are expecting a reply to a packet ID
  267. *
  268. * This only uses the most significant bits of the packet ID, both to save space
  269. * and to avoid using the higher bits that can be modified during armor() to
  270. * mask against the packet send counter used for QoS detection.
  271. *
  272. * @param packetId Packet ID to expect reply to
  273. */
  274. ZT_ALWAYS_INLINE void expectReplyTo(const uint64_t packetId)
  275. {
  276. const unsigned long pid2 = (unsigned long)(packetId >> 32U);
  277. const unsigned long bucket = (unsigned long)(pid2 & ZT_EXPECTING_REPLIES_BUCKET_MASK1);
  278. _expectingRepliesTo[bucket][_expectingRepliesToBucketPtr[bucket]++ & ZT_EXPECTING_REPLIES_BUCKET_MASK2] = (uint32_t)pid2;
  279. }
  280. /**
  281. * Check whether a given packet ID is something we are expecting a reply to
  282. *
  283. * This only uses the most significant bits of the packet ID, both to save space
  284. * and to avoid using the higher bits that can be modified during armor() to
  285. * mask against the packet send counter used for QoS detection.
  286. *
  287. * @param packetId Packet ID to check
  288. * @return True if we're expecting a reply
  289. */
  290. ZT_ALWAYS_INLINE bool expectingReplyTo(const uint64_t packetId) const
  291. {
  292. const uint32_t pid2 = (uint32_t)(packetId >> 32);
  293. const unsigned long bucket = (unsigned long)(pid2 & ZT_EXPECTING_REPLIES_BUCKET_MASK1);
  294. for(unsigned long i=0;i<=ZT_EXPECTING_REPLIES_BUCKET_MASK2;++i) {
  295. if (_expectingRepliesTo[bucket][i] == pid2)
  296. return true;
  297. }
  298. return false;
  299. }
  300. /**
  301. * Check whether we should do potentially expensive identity verification (rate limit)
  302. *
  303. * @param now Current time
  304. * @param from Source address of packet
  305. * @return True if within rate limits
  306. */
  307. ZT_ALWAYS_INLINE bool rateGateIdentityVerification(const int64_t now,const InetAddress &from)
  308. {
  309. unsigned long iph = from.rateGateHash();
  310. if ((now - _lastIdentityVerification[iph]) >= ZT_IDENTITY_VALIDATION_SOURCE_RATE_LIMIT) {
  311. _lastIdentityVerification[iph] = now;
  312. return true;
  313. }
  314. return false;
  315. }
  316. /**
  317. * Check whether a local controller has authorized a member on a network
  318. *
  319. * This is used by controllers to avoid needless certificate checks when we already
  320. * know if this has occurred. It's a bit of a hack but saves a massive amount of
  321. * controller CPU. It's easiest to put this here, and it imposes no overhead on
  322. * non-controllers.
  323. *
  324. * @param now Current time
  325. * @param nwid Network ID
  326. * @param addr Member address to check
  327. * @return True if member has been authorized
  328. */
  329. bool localControllerHasAuthorized(int64_t now,uint64_t nwid,const Address &addr) const;
  330. // Implementation of NetworkController::Sender interface
  331. virtual void ncSendConfig(uint64_t nwid,uint64_t requestPacketId,const Address &destination,const NetworkConfig &nc,bool sendLegacyFormatConfig);
  332. virtual void ncSendRevocation(const Address &destination,const Revocation &rev);
  333. virtual void ncSendError(uint64_t nwid,uint64_t requestPacketId,const Address &destination,NetworkController::ErrorCode errorCode);
  334. private:
  335. RuntimeEnvironment _RR;
  336. RuntimeEnvironment *RR;
  337. ZT_Node_Callbacks _cb;
  338. void *_uPtr; // _uptr (lower case) is reserved in Visual Studio :P
  339. // For tracking packet IDs to filter out OK/ERROR replies to packets we did not send
  340. volatile uint8_t _expectingRepliesToBucketPtr[ZT_EXPECTING_REPLIES_BUCKET_MASK1 + 1];
  341. volatile uint32_t _expectingRepliesTo[ZT_EXPECTING_REPLIES_BUCKET_MASK1 + 1][ZT_EXPECTING_REPLIES_BUCKET_MASK2 + 1];
  342. // Time of last identity verification indexed by InetAddress.rateGateHash() -- used in IncomingPacket::_doHELLO() via rateGateIdentityVerification()
  343. volatile int64_t _lastIdentityVerification[16384];
  344. /* Map that remembers if we have recently sent a network config to someone
  345. * querying us as a controller. This is an optimization to allow network
  346. * controllers to know whether to treat things like multicast queries the
  347. * way authorized members would be treated without requiring an extra cert
  348. * validation. */
  349. struct _LocalControllerAuth
  350. {
  351. uint64_t nwid,address;
  352. ZT_ALWAYS_INLINE _LocalControllerAuth(const uint64_t nwid_,const Address &address_) : nwid(nwid_),address(address_.toInt()) {}
  353. ZT_ALWAYS_INLINE unsigned long hashCode() const { return (unsigned long)(nwid ^ address); }
  354. ZT_ALWAYS_INLINE bool operator==(const _LocalControllerAuth &a) const { return ((a.nwid == nwid)&&(a.address == address)); }
  355. ZT_ALWAYS_INLINE bool operator!=(const _LocalControllerAuth &a) const { return ((a.nwid != nwid)||(a.address != address)); }
  356. };
  357. Hashtable< _LocalControllerAuth,int64_t > _localControllerAuthorizations;
  358. // Networks are stored in a flat hash table that is resized on any network ID collision. This makes
  359. // network lookup by network ID a few bitwise ops and an array index.
  360. std::vector< SharedPtr<Network> > _networks;
  361. uint64_t _networksMask;
  362. std::vector< ZT_InterfaceAddress > _localInterfaceAddresses;
  363. Mutex _localControllerAuthorizations_m;
  364. RWMutex _networks_m;
  365. Mutex _localInterfaceAddresses_m;
  366. Mutex _backgroundTasksLock;
  367. volatile int64_t _now;
  368. volatile int64_t _lastPing;
  369. volatile int64_t _lastHousekeepingRun;
  370. volatile int64_t _lastNetworkHousekeepingRun;
  371. volatile int64_t _lastPathKeepaliveCheck;
  372. volatile bool _online;
  373. };
  374. } // namespace ZeroTier
  375. #endif