2
0

Node.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  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: 2025-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. #include <stdio.h>
  14. #include <stdlib.h>
  15. #include <stdarg.h>
  16. #include <string.h>
  17. #include <stdint.h>
  18. #include "../version.h"
  19. #include "Constants.hpp"
  20. #include "SharedPtr.hpp"
  21. #include "Node.hpp"
  22. #include "RuntimeEnvironment.hpp"
  23. #include "NetworkController.hpp"
  24. #include "Switch.hpp"
  25. #include "Multicaster.hpp"
  26. #include "Topology.hpp"
  27. #include "Buffer.hpp"
  28. #include "Packet.hpp"
  29. #include "Address.hpp"
  30. #include "Identity.hpp"
  31. #include "SelfAwareness.hpp"
  32. #include "Network.hpp"
  33. #include "Trace.hpp"
  34. namespace ZeroTier {
  35. /****************************************************************************/
  36. /* Public Node interface (C++, exposed via CAPI bindings) */
  37. /****************************************************************************/
  38. Node::Node(void *uptr,void *tptr,const struct ZT_Node_Callbacks *callbacks,int64_t now) :
  39. _RR(this),
  40. RR(&_RR),
  41. _uPtr(uptr),
  42. _networks(8),
  43. _now(now),
  44. _lastPingCheck(0),
  45. _lastGratuitousPingCheck(0),
  46. _lastHousekeepingRun(0),
  47. _lastMemoizedTraceSettings(0)
  48. {
  49. if (callbacks->version != 0)
  50. throw ZT_EXCEPTION_INVALID_ARGUMENT;
  51. memcpy(&_cb,callbacks,sizeof(ZT_Node_Callbacks));
  52. // Initialize non-cryptographic PRNG from a good random source
  53. Utils::getSecureRandom((void *)_prngState,sizeof(_prngState));
  54. _online = false;
  55. memset(_expectingRepliesToBucketPtr,0,sizeof(_expectingRepliesToBucketPtr));
  56. memset(_expectingRepliesTo,0,sizeof(_expectingRepliesTo));
  57. memset(_lastIdentityVerification,0,sizeof(_lastIdentityVerification));
  58. memset((void *)(&_stats),0,sizeof(_stats));
  59. uint64_t idtmp[2];
  60. idtmp[0] = 0; idtmp[1] = 0;
  61. char tmp[2048];
  62. int n = stateObjectGet(tptr,ZT_STATE_OBJECT_IDENTITY_SECRET,idtmp,tmp,sizeof(tmp) - 1);
  63. if (n > 0) {
  64. tmp[n] = (char)0;
  65. if (RR->identity.fromString(tmp)) {
  66. RR->identity.toString(false,RR->publicIdentityStr);
  67. RR->identity.toString(true,RR->secretIdentityStr);
  68. } else {
  69. n = -1;
  70. }
  71. }
  72. if (n <= 0) {
  73. RR->identity.generate();
  74. RR->identity.toString(false,RR->publicIdentityStr);
  75. RR->identity.toString(true,RR->secretIdentityStr);
  76. idtmp[0] = RR->identity.address().toInt(); idtmp[1] = 0;
  77. stateObjectPut(tptr,ZT_STATE_OBJECT_IDENTITY_SECRET,idtmp,RR->secretIdentityStr,(unsigned int)strlen(RR->secretIdentityStr));
  78. stateObjectPut(tptr,ZT_STATE_OBJECT_IDENTITY_PUBLIC,idtmp,RR->publicIdentityStr,(unsigned int)strlen(RR->publicIdentityStr));
  79. } else {
  80. idtmp[0] = RR->identity.address().toInt(); idtmp[1] = 0;
  81. n = stateObjectGet(tptr,ZT_STATE_OBJECT_IDENTITY_PUBLIC,idtmp,tmp,sizeof(tmp) - 1);
  82. if ((n > 0)&&(n < (int)sizeof(RR->publicIdentityStr))&&(n < (int)sizeof(tmp))) {
  83. if (memcmp(tmp,RR->publicIdentityStr,n))
  84. stateObjectPut(tptr,ZT_STATE_OBJECT_IDENTITY_PUBLIC,idtmp,RR->publicIdentityStr,(unsigned int)strlen(RR->publicIdentityStr));
  85. }
  86. }
  87. char *m = (char *)0;
  88. try {
  89. const unsigned long ts = sizeof(Trace) + (((sizeof(Trace) & 0xf) != 0) ? (16 - (sizeof(Trace) & 0xf)) : 0);
  90. const unsigned long sws = sizeof(Switch) + (((sizeof(Switch) & 0xf) != 0) ? (16 - (sizeof(Switch) & 0xf)) : 0);
  91. const unsigned long mcs = sizeof(Multicaster) + (((sizeof(Multicaster) & 0xf) != 0) ? (16 - (sizeof(Multicaster) & 0xf)) : 0);
  92. const unsigned long topologys = sizeof(Topology) + (((sizeof(Topology) & 0xf) != 0) ? (16 - (sizeof(Topology) & 0xf)) : 0);
  93. const unsigned long sas = sizeof(SelfAwareness) + (((sizeof(SelfAwareness) & 0xf) != 0) ? (16 - (sizeof(SelfAwareness) & 0xf)) : 0);
  94. const unsigned long bc = sizeof(Bond) + (((sizeof(Bond) & 0xf) != 0) ? (16 - (sizeof(Bond) & 0xf)) : 0);
  95. m = reinterpret_cast<char *>(::malloc(16 + ts + sws + mcs + topologys + sas + bc));
  96. if (!m)
  97. throw std::bad_alloc();
  98. RR->rtmem = m;
  99. while (((uintptr_t)m & 0xf) != 0) ++m;
  100. RR->t = new (m) Trace(RR);
  101. m += ts;
  102. RR->sw = new (m) Switch(RR);
  103. m += sws;
  104. RR->mc = new (m) Multicaster(RR);
  105. m += mcs;
  106. RR->topology = new (m) Topology(RR,tptr);
  107. m += topologys;
  108. RR->sa = new (m) SelfAwareness(RR);
  109. m += sas;
  110. RR->bc = new (m) Bond(RR);
  111. } catch ( ... ) {
  112. if (RR->sa) RR->sa->~SelfAwareness();
  113. if (RR->topology) RR->topology->~Topology();
  114. if (RR->mc) RR->mc->~Multicaster();
  115. if (RR->sw) RR->sw->~Switch();
  116. if (RR->t) RR->t->~Trace();
  117. if (RR->bc) RR->bc->~Bond();
  118. ::free(m);
  119. throw;
  120. }
  121. postEvent(tptr,ZT_EVENT_UP);
  122. }
  123. Node::~Node()
  124. {
  125. {
  126. Mutex::Lock _l(_networks_m);
  127. _networks.clear(); // destroy all networks before shutdown
  128. }
  129. if (RR->sa) RR->sa->~SelfAwareness();
  130. if (RR->topology) RR->topology->~Topology();
  131. if (RR->mc) RR->mc->~Multicaster();
  132. if (RR->sw) RR->sw->~Switch();
  133. if (RR->t) RR->t->~Trace();
  134. if (RR->bc) RR->bc->~Bond();
  135. ::free(RR->rtmem);
  136. }
  137. ZT_ResultCode Node::processWirePacket(
  138. void *tptr,
  139. int64_t now,
  140. int64_t localSocket,
  141. const struct sockaddr_storage *remoteAddress,
  142. const void *packetData,
  143. unsigned int packetLength,
  144. volatile int64_t *nextBackgroundTaskDeadline)
  145. {
  146. _now = now;
  147. RR->sw->onRemotePacket(tptr,localSocket,*(reinterpret_cast<const InetAddress *>(remoteAddress)),packetData,packetLength);
  148. return ZT_RESULT_OK;
  149. }
  150. ZT_ResultCode Node::processVirtualNetworkFrame(
  151. void *tptr,
  152. int64_t now,
  153. uint64_t nwid,
  154. uint64_t sourceMac,
  155. uint64_t destMac,
  156. unsigned int etherType,
  157. unsigned int vlanId,
  158. const void *frameData,
  159. unsigned int frameLength,
  160. volatile int64_t *nextBackgroundTaskDeadline)
  161. {
  162. _now = now;
  163. SharedPtr<Network> nw(this->network(nwid));
  164. if (nw) {
  165. RR->sw->onLocalEthernet(tptr,nw,MAC(sourceMac),MAC(destMac),etherType,vlanId,frameData,frameLength);
  166. return ZT_RESULT_OK;
  167. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  168. }
  169. // Closure used to ping upstream and active/online peers
  170. class _PingPeersThatNeedPing
  171. {
  172. public:
  173. _PingPeersThatNeedPing(const RuntimeEnvironment *renv,void *tPtr,Hashtable< Address,std::vector<InetAddress> > &alwaysContact,int64_t now) :
  174. RR(renv),
  175. _tPtr(tPtr),
  176. _alwaysContact(alwaysContact),
  177. _now(now),
  178. _bestCurrentUpstream(RR->topology->getUpstreamPeer())
  179. {
  180. }
  181. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  182. {
  183. const std::vector<InetAddress> *const alwaysContactEndpoints = _alwaysContact.get(p->address());
  184. if (alwaysContactEndpoints) {
  185. const unsigned int sent = p->doPingAndKeepalive(_tPtr,_now);
  186. bool contacted = (sent != 0);
  187. if ((sent & 0x1) == 0) { // bit 0x1 == IPv4 sent
  188. for(unsigned long k=0,ptr=(unsigned long)RR->node->prng();k<(unsigned long)alwaysContactEndpoints->size();++k) {
  189. const InetAddress &addr = (*alwaysContactEndpoints)[ptr++ % alwaysContactEndpoints->size()];
  190. if (addr.ss_family == AF_INET) {
  191. p->sendHELLO(_tPtr,-1,addr,_now);
  192. contacted = true;
  193. break;
  194. }
  195. }
  196. }
  197. if ((sent & 0x2) == 0) { // bit 0x2 == IPv6 sent
  198. for(unsigned long k=0,ptr=(unsigned long)RR->node->prng();k<(unsigned long)alwaysContactEndpoints->size();++k) {
  199. const InetAddress &addr = (*alwaysContactEndpoints)[ptr++ % alwaysContactEndpoints->size()];
  200. if (addr.ss_family == AF_INET6) {
  201. p->sendHELLO(_tPtr,-1,addr,_now);
  202. contacted = true;
  203. break;
  204. }
  205. }
  206. }
  207. if ((!contacted)&&(_bestCurrentUpstream)) {
  208. const SharedPtr<Path> up(_bestCurrentUpstream->getAppropriatePath(_now,true));
  209. if (up)
  210. p->sendHELLO(_tPtr,up->localSocket(),up->address(),_now);
  211. }
  212. _alwaysContact.erase(p->address()); // after this we'll WHOIS all upstreams that remain
  213. } else if (p->isActive(_now)) {
  214. p->doPingAndKeepalive(_tPtr,_now);
  215. }
  216. }
  217. private:
  218. const RuntimeEnvironment *RR;
  219. void *_tPtr;
  220. Hashtable< Address,std::vector<InetAddress> > &_alwaysContact;
  221. const int64_t _now;
  222. const SharedPtr<Peer> _bestCurrentUpstream;
  223. };
  224. ZT_ResultCode Node::processBackgroundTasks(void *tptr,int64_t now,volatile int64_t *nextBackgroundTaskDeadline)
  225. {
  226. _now = now;
  227. Mutex::Lock bl(_backgroundTasksLock);
  228. // Process background bond tasks
  229. unsigned long bondCheckInterval = ZT_PING_CHECK_INVERVAL;
  230. if (RR->bc->inUse()) {
  231. bondCheckInterval = std::max(RR->bc->minReqMonitorInterval(), ZT_CORE_TIMER_TASK_GRANULARITY);
  232. if ((now - _lastGratuitousPingCheck) >= ZT_CORE_TIMER_TASK_GRANULARITY) {
  233. _lastGratuitousPingCheck = now;
  234. RR->bc->processBackgroundTasks(tptr, now);
  235. }
  236. }
  237. unsigned long timeUntilNextPingCheck = ZT_PING_CHECK_INVERVAL;
  238. const int64_t timeSinceLastPingCheck = now - _lastPingCheck;
  239. if (timeSinceLastPingCheck >= timeUntilNextPingCheck) {
  240. try {
  241. _lastPingCheck = now;
  242. // Get designated VL1 upstreams
  243. Hashtable< Address,std::vector<InetAddress> > alwaysContact;
  244. RR->topology->getUpstreamsToContact(alwaysContact);
  245. // Uncomment to dump stats
  246. /*
  247. for(unsigned int i=0;i<32;i++) {
  248. if (_stats.inVerbCounts[i] > 0)
  249. printf("%.2x\t%12lld %lld\n",i,(unsigned long long)_stats.inVerbCounts[i],(unsigned long long)_stats.inVerbBytes[i]);
  250. }
  251. printf("\n");
  252. */
  253. // Check last receive time on designated upstreams to see if we seem to be online
  254. int64_t lastReceivedFromUpstream = 0;
  255. {
  256. Hashtable< Address,std::vector<InetAddress> >::Iterator i(alwaysContact);
  257. Address *upstreamAddress = (Address *)0;
  258. std::vector<InetAddress> *upstreamStableEndpoints = (std::vector<InetAddress> *)0;
  259. while (i.next(upstreamAddress,upstreamStableEndpoints)) {
  260. SharedPtr<Peer> p(RR->topology->getPeerNoCache(*upstreamAddress));
  261. if (p)
  262. lastReceivedFromUpstream = std::max(p->lastReceive(),lastReceivedFromUpstream);
  263. }
  264. }
  265. // Clean up any old local controller auth memorizations.
  266. {
  267. _localControllerAuthorizations_m.lock();
  268. Hashtable< _LocalControllerAuth,int64_t >::Iterator i(_localControllerAuthorizations);
  269. _LocalControllerAuth *k = (_LocalControllerAuth *)0;
  270. int64_t *v = (int64_t *)0;
  271. while (i.next(k,v)) {
  272. if ((*v - now) > (ZT_NETWORK_AUTOCONF_DELAY * 3))
  273. _localControllerAuthorizations.erase(*k);
  274. }
  275. _localControllerAuthorizations_m.unlock();
  276. }
  277. // Get peers we should stay connected to according to network configs
  278. // Also get networks and whether they need config so we only have to do one pass over networks
  279. std::vector< std::pair< SharedPtr<Network>,bool > > networkConfigNeeded;
  280. {
  281. Mutex::Lock l(_networks_m);
  282. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(_networks);
  283. uint64_t *nwid = (uint64_t *)0;
  284. SharedPtr<Network> *network = (SharedPtr<Network> *)0;
  285. while (i.next(nwid,network)) {
  286. (*network)->config().alwaysContactAddresses(alwaysContact);
  287. networkConfigNeeded.push_back( std::pair< SharedPtr<Network>,bool >(*network,(((now - (*network)->lastConfigUpdate()) >= ZT_NETWORK_AUTOCONF_DELAY)||(!(*network)->hasConfig()))) );
  288. }
  289. }
  290. // Ping active peers, upstreams, and others that we should always contact
  291. _PingPeersThatNeedPing pfunc(RR,tptr,alwaysContact,now);
  292. RR->topology->eachPeer<_PingPeersThatNeedPing &>(pfunc);
  293. // Run WHOIS to create Peer for alwaysContact addresses that could not be contacted
  294. {
  295. Hashtable< Address,std::vector<InetAddress> >::Iterator i(alwaysContact);
  296. Address *upstreamAddress = (Address *)0;
  297. std::vector<InetAddress> *upstreamStableEndpoints = (std::vector<InetAddress> *)0;
  298. while (i.next(upstreamAddress,upstreamStableEndpoints))
  299. RR->sw->requestWhois(tptr,now,*upstreamAddress);
  300. }
  301. // Refresh network config or broadcast network updates to members as needed
  302. for(std::vector< std::pair< SharedPtr<Network>,bool > >::const_iterator n(networkConfigNeeded.begin());n!=networkConfigNeeded.end();++n) {
  303. if (n->second)
  304. n->first->requestConfiguration(tptr);
  305. n->first->sendUpdatesToMembers(tptr);
  306. }
  307. // Update online status, post status change as event
  308. const bool oldOnline = _online;
  309. _online = (((now - lastReceivedFromUpstream) < ZT_PEER_ACTIVITY_TIMEOUT)||(RR->topology->amUpstream()));
  310. if (oldOnline != _online)
  311. postEvent(tptr,_online ? ZT_EVENT_ONLINE : ZT_EVENT_OFFLINE);
  312. } catch ( ... ) {
  313. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  314. }
  315. } else {
  316. timeUntilNextPingCheck -= (unsigned long)timeSinceLastPingCheck;
  317. }
  318. if ((now - _lastMemoizedTraceSettings) >= (ZT_HOUSEKEEPING_PERIOD / 4)) {
  319. _lastMemoizedTraceSettings = now;
  320. RR->t->updateMemoizedSettings();
  321. }
  322. if ((now - _lastHousekeepingRun) >= ZT_HOUSEKEEPING_PERIOD) {
  323. _lastHousekeepingRun = now;
  324. try {
  325. RR->topology->doPeriodicTasks(tptr,now);
  326. RR->sa->clean(now);
  327. RR->mc->clean(now);
  328. } catch ( ... ) {
  329. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  330. }
  331. }
  332. try {
  333. *nextBackgroundTaskDeadline = now + (int64_t)std::max(std::min(bondCheckInterval,std::min(timeUntilNextPingCheck,RR->sw->doTimerTasks(tptr,now))),(unsigned long)ZT_CORE_TIMER_TASK_GRANULARITY);
  334. } catch ( ... ) {
  335. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  336. }
  337. return ZT_RESULT_OK;
  338. }
  339. ZT_ResultCode Node::join(uint64_t nwid,void *uptr,void *tptr)
  340. {
  341. Mutex::Lock _l(_networks_m);
  342. SharedPtr<Network> &nw = _networks[nwid];
  343. if (!nw)
  344. nw = SharedPtr<Network>(new Network(RR,tptr,nwid,uptr,(const NetworkConfig *)0));
  345. return ZT_RESULT_OK;
  346. }
  347. ZT_ResultCode Node::leave(uint64_t nwid,void **uptr,void *tptr)
  348. {
  349. ZT_VirtualNetworkConfig ctmp;
  350. void **nUserPtr = (void **)0;
  351. {
  352. Mutex::Lock _l(_networks_m);
  353. SharedPtr<Network> *nw = _networks.get(nwid);
  354. RR->sw->removeNetworkQoSControlBlock(nwid);
  355. if (!nw)
  356. return ZT_RESULT_OK;
  357. if (uptr)
  358. *uptr = (*nw)->userPtr();
  359. (*nw)->externalConfig(&ctmp);
  360. (*nw)->destroy();
  361. nUserPtr = (*nw)->userPtr();
  362. }
  363. if (nUserPtr)
  364. RR->node->configureVirtualNetworkPort(tptr,nwid,nUserPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
  365. {
  366. Mutex::Lock _l(_networks_m);
  367. _networks.erase(nwid);
  368. }
  369. uint64_t tmp[2];
  370. tmp[0] = nwid; tmp[1] = 0;
  371. RR->node->stateObjectDelete(tptr,ZT_STATE_OBJECT_NETWORK_CONFIG,tmp);
  372. return ZT_RESULT_OK;
  373. }
  374. ZT_ResultCode Node::multicastSubscribe(void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  375. {
  376. SharedPtr<Network> nw(this->network(nwid));
  377. if (nw) {
  378. nw->multicastSubscribe(tptr,MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  379. return ZT_RESULT_OK;
  380. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  381. }
  382. ZT_ResultCode Node::multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  383. {
  384. SharedPtr<Network> nw(this->network(nwid));
  385. if (nw) {
  386. nw->multicastUnsubscribe(MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  387. return ZT_RESULT_OK;
  388. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  389. }
  390. ZT_ResultCode Node::orbit(void *tptr,uint64_t moonWorldId,uint64_t moonSeed)
  391. {
  392. RR->topology->addMoon(tptr,moonWorldId,Address(moonSeed));
  393. return ZT_RESULT_OK;
  394. }
  395. ZT_ResultCode Node::deorbit(void *tptr,uint64_t moonWorldId)
  396. {
  397. RR->topology->removeMoon(tptr,moonWorldId);
  398. return ZT_RESULT_OK;
  399. }
  400. uint64_t Node::address() const
  401. {
  402. return RR->identity.address().toInt();
  403. }
  404. void Node::status(ZT_NodeStatus *status) const
  405. {
  406. status->address = RR->identity.address().toInt();
  407. status->publicIdentity = RR->publicIdentityStr;
  408. status->secretIdentity = RR->secretIdentityStr;
  409. status->online = _online ? 1 : 0;
  410. }
  411. ZT_PeerList *Node::peers() const
  412. {
  413. std::vector< std::pair< Address,SharedPtr<Peer> > > peers(RR->topology->allPeers());
  414. std::sort(peers.begin(),peers.end());
  415. char *buf = (char *)::malloc(sizeof(ZT_PeerList) + (sizeof(ZT_Peer) * peers.size()));
  416. if (!buf)
  417. return (ZT_PeerList *)0;
  418. ZT_PeerList *pl = (ZT_PeerList *)buf;
  419. pl->peers = (ZT_Peer *)(buf + sizeof(ZT_PeerList));
  420. pl->peerCount = 0;
  421. for(std::vector< std::pair< Address,SharedPtr<Peer> > >::iterator pi(peers.begin());pi!=peers.end();++pi) {
  422. ZT_Peer *p = &(pl->peers[pl->peerCount++]);
  423. p->address = pi->second->address().toInt();
  424. p->isBonded = 0;
  425. if (pi->second->remoteVersionKnown()) {
  426. p->versionMajor = pi->second->remoteVersionMajor();
  427. p->versionMinor = pi->second->remoteVersionMinor();
  428. p->versionRev = pi->second->remoteVersionRevision();
  429. } else {
  430. p->versionMajor = -1;
  431. p->versionMinor = -1;
  432. p->versionRev = -1;
  433. }
  434. p->latency = pi->second->latency(_now);
  435. if (p->latency >= 0xffff)
  436. p->latency = -1;
  437. p->role = RR->topology->role(pi->second->identity().address());
  438. std::vector< SharedPtr<Path> > paths(pi->second->paths(_now));
  439. SharedPtr<Path> bestp(pi->second->getAppropriatePath(_now,false));
  440. p->pathCount = 0;
  441. for(std::vector< SharedPtr<Path> >::iterator path(paths.begin());path!=paths.end();++path) {
  442. memcpy(&(p->paths[p->pathCount].address),&((*path)->address()),sizeof(struct sockaddr_storage));
  443. p->paths[p->pathCount].localSocket = (*path)->localSocket();
  444. p->paths[p->pathCount].lastSend = (*path)->lastOut();
  445. p->paths[p->pathCount].lastReceive = (*path)->lastIn();
  446. p->paths[p->pathCount].trustedPathId = RR->topology->getOutboundPathTrust((*path)->address());
  447. p->paths[p->pathCount].expired = 0;
  448. p->paths[p->pathCount].preferred = ((*path) == bestp) ? 1 : 0;
  449. p->paths[p->pathCount].scope = (*path)->ipScope();
  450. ++p->pathCount;
  451. }
  452. if (pi->second->bond()) {
  453. p->isBonded = pi->second->bond();
  454. p->bondingPolicy = pi->second->bond()->policy();
  455. p->numAliveLinks = pi->second->bond()->getNumAliveLinks();
  456. p->numTotalLinks = pi->second->bond()->getNumTotalLinks();
  457. }
  458. }
  459. return pl;
  460. }
  461. ZT_VirtualNetworkConfig *Node::networkConfig(uint64_t nwid) const
  462. {
  463. Mutex::Lock _l(_networks_m);
  464. const SharedPtr<Network> *nw = _networks.get(nwid);
  465. if (nw) {
  466. ZT_VirtualNetworkConfig *nc = (ZT_VirtualNetworkConfig *)::malloc(sizeof(ZT_VirtualNetworkConfig));
  467. (*nw)->externalConfig(nc);
  468. return nc;
  469. }
  470. return (ZT_VirtualNetworkConfig *)0;
  471. }
  472. ZT_VirtualNetworkList *Node::networks() const
  473. {
  474. Mutex::Lock _l(_networks_m);
  475. char *buf = (char *)::malloc(sizeof(ZT_VirtualNetworkList) + (sizeof(ZT_VirtualNetworkConfig) * _networks.size()));
  476. if (!buf)
  477. return (ZT_VirtualNetworkList *)0;
  478. ZT_VirtualNetworkList *nl = (ZT_VirtualNetworkList *)buf;
  479. nl->networks = (ZT_VirtualNetworkConfig *)(buf + sizeof(ZT_VirtualNetworkList));
  480. nl->networkCount = 0;
  481. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(*const_cast< Hashtable< uint64_t,SharedPtr<Network> > *>(&_networks));
  482. uint64_t *k = (uint64_t *)0;
  483. SharedPtr<Network> *v = (SharedPtr<Network> *)0;
  484. while (i.next(k,v))
  485. (*v)->externalConfig(&(nl->networks[nl->networkCount++]));
  486. return nl;
  487. }
  488. void Node::freeQueryResult(void *qr)
  489. {
  490. if (qr)
  491. ::free(qr);
  492. }
  493. int Node::addLocalInterfaceAddress(const struct sockaddr_storage *addr)
  494. {
  495. if (Path::isAddressValidForPath(*(reinterpret_cast<const InetAddress *>(addr)))) {
  496. Mutex::Lock _l(_directPaths_m);
  497. if (std::find(_directPaths.begin(),_directPaths.end(),*(reinterpret_cast<const InetAddress *>(addr))) == _directPaths.end()) {
  498. _directPaths.push_back(*(reinterpret_cast<const InetAddress *>(addr)));
  499. return 1;
  500. }
  501. }
  502. return 0;
  503. }
  504. void Node::clearLocalInterfaceAddresses()
  505. {
  506. Mutex::Lock _l(_directPaths_m);
  507. _directPaths.clear();
  508. }
  509. int Node::sendUserMessage(void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len)
  510. {
  511. try {
  512. if (RR->identity.address().toInt() != dest) {
  513. Packet outp(Address(dest),RR->identity.address(),Packet::VERB_USER_MESSAGE);
  514. outp.append(typeId);
  515. outp.append(data,len);
  516. outp.compress();
  517. RR->sw->send(tptr,outp,true);
  518. return 1;
  519. }
  520. } catch ( ... ) {}
  521. return 0;
  522. }
  523. void Node::setNetconfMaster(void *networkControllerInstance)
  524. {
  525. RR->localNetworkController = reinterpret_cast<NetworkController *>(networkControllerInstance);
  526. if (networkControllerInstance)
  527. RR->localNetworkController->init(RR->identity,this);
  528. }
  529. /****************************************************************************/
  530. /* Node methods used only within node/ */
  531. /****************************************************************************/
  532. bool Node::shouldUsePathForZeroTierTraffic(void *tPtr,const Address &ztaddr,const int64_t localSocket,const InetAddress &remoteAddress)
  533. {
  534. if (!Path::isAddressValidForPath(remoteAddress))
  535. return false;
  536. if (RR->topology->isProhibitedEndpoint(ztaddr,remoteAddress))
  537. return false;
  538. {
  539. Mutex::Lock _l(_networks_m);
  540. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(_networks);
  541. uint64_t *k = (uint64_t *)0;
  542. SharedPtr<Network> *v = (SharedPtr<Network> *)0;
  543. while (i.next(k,v)) {
  544. if ((*v)->hasConfig()) {
  545. for(unsigned int k=0;k<(*v)->config().staticIpCount;++k) {
  546. if ((*v)->config().staticIps[k].containsAddress(remoteAddress))
  547. return false;
  548. }
  549. }
  550. }
  551. }
  552. return ( (_cb.pathCheckFunction) ? (_cb.pathCheckFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,ztaddr.toInt(),localSocket,reinterpret_cast<const struct sockaddr_storage *>(&remoteAddress)) != 0) : true);
  553. }
  554. uint64_t Node::prng()
  555. {
  556. // https://en.wikipedia.org/wiki/Xorshift#xorshift.2B
  557. uint64_t x = _prngState[0];
  558. const uint64_t y = _prngState[1];
  559. _prngState[0] = y;
  560. x ^= x << 23;
  561. const uint64_t z = x ^ y ^ (x >> 17) ^ (y >> 26);
  562. _prngState[1] = z;
  563. return z + y;
  564. }
  565. ZT_ResultCode Node::setPhysicalPathConfiguration(const struct sockaddr_storage *pathNetwork, const ZT_PhysicalPathConfiguration *pathConfig)
  566. {
  567. RR->topology->setPhysicalPathConfiguration(pathNetwork,pathConfig);
  568. return ZT_RESULT_OK;
  569. }
  570. World Node::planet() const
  571. {
  572. return RR->topology->planet();
  573. }
  574. std::vector<World> Node::moons() const
  575. {
  576. return RR->topology->moons();
  577. }
  578. void Node::ncSendConfig(uint64_t nwid,uint64_t requestPacketId,const Address &destination,const NetworkConfig &nc,bool sendLegacyFormatConfig)
  579. {
  580. _localControllerAuthorizations_m.lock();
  581. _localControllerAuthorizations[_LocalControllerAuth(nwid,destination)] = now();
  582. _localControllerAuthorizations_m.unlock();
  583. if (destination == RR->identity.address()) {
  584. SharedPtr<Network> n(network(nwid));
  585. if (!n) return;
  586. n->setConfiguration((void *)0,nc,true);
  587. } else {
  588. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *dconf = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>();
  589. try {
  590. if (nc.toDictionary(*dconf,sendLegacyFormatConfig)) {
  591. uint64_t configUpdateId = prng();
  592. if (!configUpdateId) ++configUpdateId;
  593. const unsigned int totalSize = dconf->sizeBytes();
  594. unsigned int chunkIndex = 0;
  595. while (chunkIndex < totalSize) {
  596. const unsigned int chunkLen = std::min(totalSize - chunkIndex,(unsigned int)(ZT_PROTO_MAX_PACKET_LENGTH - (ZT_PACKET_IDX_PAYLOAD + 256)));
  597. Packet outp(destination,RR->identity.address(),(requestPacketId) ? Packet::VERB_OK : Packet::VERB_NETWORK_CONFIG);
  598. if (requestPacketId) {
  599. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  600. outp.append(requestPacketId);
  601. }
  602. const unsigned int sigStart = outp.size();
  603. outp.append(nwid);
  604. outp.append((uint16_t)chunkLen);
  605. outp.append((const void *)(dconf->data() + chunkIndex),chunkLen);
  606. outp.append((uint8_t)0); // no flags
  607. outp.append((uint64_t)configUpdateId);
  608. outp.append((uint32_t)totalSize);
  609. outp.append((uint32_t)chunkIndex);
  610. C25519::Signature sig(RR->identity.sign(reinterpret_cast<const uint8_t *>(outp.data()) + sigStart,outp.size() - sigStart));
  611. outp.append((uint8_t)1);
  612. outp.append((uint16_t)ZT_C25519_SIGNATURE_LEN);
  613. outp.append(sig.data,ZT_C25519_SIGNATURE_LEN);
  614. outp.compress();
  615. RR->sw->send((void *)0,outp,true);
  616. chunkIndex += chunkLen;
  617. }
  618. }
  619. delete dconf;
  620. } catch ( ... ) {
  621. delete dconf;
  622. throw;
  623. }
  624. }
  625. }
  626. void Node::ncSendRevocation(const Address &destination,const Revocation &rev)
  627. {
  628. if (destination == RR->identity.address()) {
  629. SharedPtr<Network> n(network(rev.networkId()));
  630. if (!n) return;
  631. n->addCredential((void *)0,RR->identity.address(),rev);
  632. } else {
  633. Packet outp(destination,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  634. outp.append((uint8_t)0x00);
  635. outp.append((uint16_t)0);
  636. outp.append((uint16_t)0);
  637. outp.append((uint16_t)1);
  638. rev.serialize(outp);
  639. outp.append((uint16_t)0);
  640. RR->sw->send((void *)0,outp,true);
  641. }
  642. }
  643. void Node::ncSendError(uint64_t nwid,uint64_t requestPacketId,const Address &destination,NetworkController::ErrorCode errorCode, const void *errorData, unsigned int errorDataSize)
  644. {
  645. if (destination == RR->identity.address()) {
  646. SharedPtr<Network> n(network(nwid));
  647. if (!n) return;
  648. switch(errorCode) {
  649. case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  650. case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  651. n->setNotFound(nullptr);
  652. break;
  653. case NetworkController::NC_ERROR_ACCESS_DENIED:
  654. n->setAccessDenied(nullptr);
  655. break;
  656. case NetworkController::NC_ERROR_AUTHENTICATION_REQUIRED: {
  657. //fprintf(stderr, "\n\nGot auth required\n\n");
  658. break;
  659. }
  660. default: break;
  661. }
  662. } else if (requestPacketId) {
  663. Packet outp(destination,RR->identity.address(),Packet::VERB_ERROR);
  664. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  665. outp.append(requestPacketId);
  666. switch(errorCode) {
  667. //case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  668. //case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  669. default:
  670. outp.append((unsigned char)Packet::ERROR_OBJ_NOT_FOUND);
  671. break;
  672. case NetworkController::NC_ERROR_ACCESS_DENIED:
  673. outp.append((unsigned char)Packet::ERROR_NETWORK_ACCESS_DENIED_);
  674. break;
  675. case NetworkController::NC_ERROR_AUTHENTICATION_REQUIRED:
  676. outp.append((unsigned char)Packet::ERROR_NETWORK_AUTHENTICATION_REQUIRED);
  677. break;
  678. }
  679. outp.append(nwid);
  680. if ((errorData)&&(errorDataSize > 0)&&(errorDataSize <= 0xffff)) {
  681. outp.append((uint16_t)errorDataSize);
  682. outp.append(errorData, errorDataSize);
  683. }
  684. RR->sw->send((void *)0,outp,true);
  685. } // else we can't send an ERROR() in response to nothing, so discard
  686. }
  687. } // namespace ZeroTier
  688. /****************************************************************************/
  689. /* CAPI bindings */
  690. /****************************************************************************/
  691. extern "C" {
  692. enum ZT_ResultCode ZT_Node_new(ZT_Node **node,void *uptr,void *tptr,const struct ZT_Node_Callbacks *callbacks,int64_t now)
  693. {
  694. *node = (ZT_Node *)0;
  695. try {
  696. *node = reinterpret_cast<ZT_Node *>(new ZeroTier::Node(uptr,tptr,callbacks,now));
  697. return ZT_RESULT_OK;
  698. } catch (std::bad_alloc &exc) {
  699. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  700. } catch (std::runtime_error &exc) {
  701. return ZT_RESULT_FATAL_ERROR_DATA_STORE_FAILED;
  702. } catch ( ... ) {
  703. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  704. }
  705. }
  706. void ZT_Node_delete(ZT_Node *node)
  707. {
  708. try {
  709. delete (reinterpret_cast<ZeroTier::Node *>(node));
  710. } catch ( ... ) {}
  711. }
  712. enum ZT_ResultCode ZT_Node_processWirePacket(
  713. ZT_Node *node,
  714. void *tptr,
  715. int64_t now,
  716. int64_t localSocket,
  717. const struct sockaddr_storage *remoteAddress,
  718. const void *packetData,
  719. unsigned int packetLength,
  720. volatile int64_t *nextBackgroundTaskDeadline)
  721. {
  722. try {
  723. return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(tptr,now,localSocket,remoteAddress,packetData,packetLength,nextBackgroundTaskDeadline);
  724. } catch (std::bad_alloc &exc) {
  725. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  726. } catch ( ... ) {
  727. return ZT_RESULT_OK; // "OK" since invalid packets are simply dropped, but the system is still up
  728. }
  729. }
  730. enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame(
  731. ZT_Node *node,
  732. void *tptr,
  733. int64_t now,
  734. uint64_t nwid,
  735. uint64_t sourceMac,
  736. uint64_t destMac,
  737. unsigned int etherType,
  738. unsigned int vlanId,
  739. const void *frameData,
  740. unsigned int frameLength,
  741. volatile int64_t *nextBackgroundTaskDeadline)
  742. {
  743. try {
  744. return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(tptr,now,nwid,sourceMac,destMac,etherType,vlanId,frameData,frameLength,nextBackgroundTaskDeadline);
  745. } catch (std::bad_alloc &exc) {
  746. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  747. } catch ( ... ) {
  748. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  749. }
  750. }
  751. enum ZT_ResultCode ZT_Node_processBackgroundTasks(ZT_Node *node,void *tptr,int64_t now,volatile int64_t *nextBackgroundTaskDeadline)
  752. {
  753. try {
  754. return reinterpret_cast<ZeroTier::Node *>(node)->processBackgroundTasks(tptr,now,nextBackgroundTaskDeadline);
  755. } catch (std::bad_alloc &exc) {
  756. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  757. } catch ( ... ) {
  758. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  759. }
  760. }
  761. enum ZT_ResultCode ZT_Node_join(ZT_Node *node,uint64_t nwid,void *uptr,void *tptr)
  762. {
  763. try {
  764. return reinterpret_cast<ZeroTier::Node *>(node)->join(nwid,uptr,tptr);
  765. } catch (std::bad_alloc &exc) {
  766. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  767. } catch ( ... ) {
  768. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  769. }
  770. }
  771. enum ZT_ResultCode ZT_Node_leave(ZT_Node *node,uint64_t nwid,void **uptr,void *tptr)
  772. {
  773. try {
  774. return reinterpret_cast<ZeroTier::Node *>(node)->leave(nwid,uptr,tptr);
  775. } catch (std::bad_alloc &exc) {
  776. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  777. } catch ( ... ) {
  778. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  779. }
  780. }
  781. enum ZT_ResultCode ZT_Node_multicastSubscribe(ZT_Node *node,void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  782. {
  783. try {
  784. return reinterpret_cast<ZeroTier::Node *>(node)->multicastSubscribe(tptr,nwid,multicastGroup,multicastAdi);
  785. } catch (std::bad_alloc &exc) {
  786. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  787. } catch ( ... ) {
  788. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  789. }
  790. }
  791. enum ZT_ResultCode ZT_Node_multicastUnsubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  792. {
  793. try {
  794. return reinterpret_cast<ZeroTier::Node *>(node)->multicastUnsubscribe(nwid,multicastGroup,multicastAdi);
  795. } catch (std::bad_alloc &exc) {
  796. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  797. } catch ( ... ) {
  798. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  799. }
  800. }
  801. enum ZT_ResultCode ZT_Node_orbit(ZT_Node *node,void *tptr,uint64_t moonWorldId,uint64_t moonSeed)
  802. {
  803. try {
  804. return reinterpret_cast<ZeroTier::Node *>(node)->orbit(tptr,moonWorldId,moonSeed);
  805. } catch ( ... ) {
  806. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  807. }
  808. }
  809. enum ZT_ResultCode ZT_Node_deorbit(ZT_Node *node,void *tptr,uint64_t moonWorldId)
  810. {
  811. try {
  812. return reinterpret_cast<ZeroTier::Node *>(node)->deorbit(tptr,moonWorldId);
  813. } catch ( ... ) {
  814. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  815. }
  816. }
  817. uint64_t ZT_Node_address(ZT_Node *node)
  818. {
  819. return reinterpret_cast<ZeroTier::Node *>(node)->address();
  820. }
  821. void ZT_Node_status(ZT_Node *node,ZT_NodeStatus *status)
  822. {
  823. try {
  824. reinterpret_cast<ZeroTier::Node *>(node)->status(status);
  825. } catch ( ... ) {}
  826. }
  827. ZT_PeerList *ZT_Node_peers(ZT_Node *node)
  828. {
  829. try {
  830. return reinterpret_cast<ZeroTier::Node *>(node)->peers();
  831. } catch ( ... ) {
  832. return (ZT_PeerList *)0;
  833. }
  834. }
  835. ZT_VirtualNetworkConfig *ZT_Node_networkConfig(ZT_Node *node,uint64_t nwid)
  836. {
  837. try {
  838. return reinterpret_cast<ZeroTier::Node *>(node)->networkConfig(nwid);
  839. } catch ( ... ) {
  840. return (ZT_VirtualNetworkConfig *)0;
  841. }
  842. }
  843. ZT_VirtualNetworkList *ZT_Node_networks(ZT_Node *node)
  844. {
  845. try {
  846. return reinterpret_cast<ZeroTier::Node *>(node)->networks();
  847. } catch ( ... ) {
  848. return (ZT_VirtualNetworkList *)0;
  849. }
  850. }
  851. void ZT_Node_freeQueryResult(ZT_Node *node,void *qr)
  852. {
  853. try {
  854. reinterpret_cast<ZeroTier::Node *>(node)->freeQueryResult(qr);
  855. } catch ( ... ) {}
  856. }
  857. int ZT_Node_addLocalInterfaceAddress(ZT_Node *node,const struct sockaddr_storage *addr)
  858. {
  859. try {
  860. return reinterpret_cast<ZeroTier::Node *>(node)->addLocalInterfaceAddress(addr);
  861. } catch ( ... ) {
  862. return 0;
  863. }
  864. }
  865. void ZT_Node_clearLocalInterfaceAddresses(ZT_Node *node)
  866. {
  867. try {
  868. reinterpret_cast<ZeroTier::Node *>(node)->clearLocalInterfaceAddresses();
  869. } catch ( ... ) {}
  870. }
  871. int ZT_Node_sendUserMessage(ZT_Node *node,void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len)
  872. {
  873. try {
  874. return reinterpret_cast<ZeroTier::Node *>(node)->sendUserMessage(tptr,dest,typeId,data,len);
  875. } catch ( ... ) {
  876. return 0;
  877. }
  878. }
  879. void ZT_Node_setNetconfMaster(ZT_Node *node,void *networkControllerInstance)
  880. {
  881. try {
  882. reinterpret_cast<ZeroTier::Node *>(node)->setNetconfMaster(networkControllerInstance);
  883. } catch ( ... ) {}
  884. }
  885. enum ZT_ResultCode ZT_Node_setPhysicalPathConfiguration(ZT_Node *node,const struct sockaddr_storage *pathNetwork,const ZT_PhysicalPathConfiguration *pathConfig)
  886. {
  887. try {
  888. return reinterpret_cast<ZeroTier::Node *>(node)->setPhysicalPathConfiguration(pathNetwork,pathConfig);
  889. } catch ( ... ) {
  890. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  891. }
  892. }
  893. void ZT_version(int *major,int *minor,int *revision)
  894. {
  895. if (major) *major = ZEROTIER_ONE_VERSION_MAJOR;
  896. if (minor) *minor = ZEROTIER_ONE_VERSION_MINOR;
  897. if (revision) *revision = ZEROTIER_ONE_VERSION_REVISION;
  898. }
  899. } // extern "C"