Node.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  1. /*
  2. * Copyright (c)2019 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: 2023-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 "Constants.hpp"
  19. #include "SharedPtr.hpp"
  20. #include "Node.hpp"
  21. #include "RuntimeEnvironment.hpp"
  22. #include "NetworkController.hpp"
  23. #include "Switch.hpp"
  24. #include "Multicaster.hpp"
  25. #include "Topology.hpp"
  26. #include "Buffer.hpp"
  27. #include "Packet.hpp"
  28. #include "Address.hpp"
  29. #include "Identity.hpp"
  30. #include "SelfAwareness.hpp"
  31. #include "Network.hpp"
  32. #include "Trace.hpp"
  33. #include "ScopedPtr.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. _lastPing(0),
  45. _lastHousekeepingRun(0),
  46. _lastNetworkHousekeepingRun(0)
  47. {
  48. memcpy(&_cb,callbacks,sizeof(ZT_Node_Callbacks));
  49. _online = false;
  50. memset(_expectingRepliesToBucketPtr,0,sizeof(_expectingRepliesToBucketPtr));
  51. memset(_expectingRepliesTo,0,sizeof(_expectingRepliesTo));
  52. memset(_lastIdentityVerification,0,sizeof(_lastIdentityVerification));
  53. uint64_t idtmp[2];
  54. idtmp[0] = 0; idtmp[1] = 0;
  55. char tmp[2048];
  56. int n = stateObjectGet(tptr,ZT_STATE_OBJECT_IDENTITY_SECRET,idtmp,tmp,sizeof(tmp) - 1);
  57. if (n > 0) {
  58. tmp[n] = (char)0;
  59. if (RR->identity.fromString(tmp)) {
  60. RR->identity.toString(false,RR->publicIdentityStr);
  61. RR->identity.toString(true,RR->secretIdentityStr);
  62. } else {
  63. n = -1;
  64. }
  65. }
  66. if (n <= 0) {
  67. RR->identity.generate(Identity::C25519);
  68. RR->identity.toString(false,RR->publicIdentityStr);
  69. RR->identity.toString(true,RR->secretIdentityStr);
  70. idtmp[0] = RR->identity.address().toInt(); idtmp[1] = 0;
  71. stateObjectPut(tptr,ZT_STATE_OBJECT_IDENTITY_SECRET,idtmp,RR->secretIdentityStr,(unsigned int)strlen(RR->secretIdentityStr));
  72. stateObjectPut(tptr,ZT_STATE_OBJECT_IDENTITY_PUBLIC,idtmp,RR->publicIdentityStr,(unsigned int)strlen(RR->publicIdentityStr));
  73. } else {
  74. idtmp[0] = RR->identity.address().toInt(); idtmp[1] = 0;
  75. n = stateObjectGet(tptr,ZT_STATE_OBJECT_IDENTITY_PUBLIC,idtmp,tmp,sizeof(tmp) - 1);
  76. if ((n > 0)&&(n < (int)sizeof(RR->publicIdentityStr))&&(n < (int)sizeof(tmp))) {
  77. if (memcmp(tmp,RR->publicIdentityStr,n))
  78. stateObjectPut(tptr,ZT_STATE_OBJECT_IDENTITY_PUBLIC,idtmp,RR->publicIdentityStr,(unsigned int)strlen(RR->publicIdentityStr));
  79. }
  80. }
  81. char *m = (char *)0;
  82. try {
  83. const unsigned long ts = sizeof(Trace) + (((sizeof(Trace) & 0xf) != 0) ? (16 - (sizeof(Trace) & 0xf)) : 0);
  84. const unsigned long sws = sizeof(Switch) + (((sizeof(Switch) & 0xf) != 0) ? (16 - (sizeof(Switch) & 0xf)) : 0);
  85. const unsigned long mcs = sizeof(Multicaster) + (((sizeof(Multicaster) & 0xf) != 0) ? (16 - (sizeof(Multicaster) & 0xf)) : 0);
  86. const unsigned long topologys = sizeof(Topology) + (((sizeof(Topology) & 0xf) != 0) ? (16 - (sizeof(Topology) & 0xf)) : 0);
  87. const unsigned long sas = sizeof(SelfAwareness) + (((sizeof(SelfAwareness) & 0xf) != 0) ? (16 - (sizeof(SelfAwareness) & 0xf)) : 0);
  88. m = reinterpret_cast<char *>(::malloc(16 + ts + sws + mcs + topologys + sas));
  89. if (!m)
  90. throw std::bad_alloc();
  91. RR->rtmem = m;
  92. while (((uintptr_t)m & 0xf) != 0) ++m;
  93. RR->t = new (m) Trace(RR);
  94. m += ts;
  95. RR->sw = new (m) Switch(RR);
  96. m += sws;
  97. RR->mc = new (m) Multicaster(RR);
  98. m += mcs;
  99. RR->topology = new (m) Topology(RR,RR->identity);
  100. m += topologys;
  101. RR->sa = new (m) SelfAwareness(RR);
  102. } catch ( ... ) {
  103. if (RR->sa) RR->sa->~SelfAwareness();
  104. if (RR->topology) RR->topology->~Topology();
  105. if (RR->mc) RR->mc->~Multicaster();
  106. if (RR->sw) RR->sw->~Switch();
  107. if (RR->t) RR->t->~Trace();
  108. ::free(m);
  109. throw;
  110. }
  111. postEvent(tptr,ZT_EVENT_UP);
  112. }
  113. Node::~Node()
  114. {
  115. {
  116. Mutex::Lock _l(_networks_m);
  117. _networks.clear(); // destroy all networks before shutdown
  118. }
  119. if (RR->sa) RR->sa->~SelfAwareness();
  120. if (RR->topology) RR->topology->~Topology();
  121. if (RR->mc) RR->mc->~Multicaster();
  122. if (RR->sw) RR->sw->~Switch();
  123. if (RR->t) RR->t->~Trace();
  124. ::free(RR->rtmem);
  125. }
  126. ZT_ResultCode Node::processWirePacket(
  127. void *tptr,
  128. int64_t now,
  129. int64_t localSocket,
  130. const struct sockaddr_storage *remoteAddress,
  131. const void *packetData,
  132. unsigned int packetLength,
  133. volatile int64_t *nextBackgroundTaskDeadline)
  134. {
  135. _now = now;
  136. RR->sw->onRemotePacket(tptr,localSocket,*(reinterpret_cast<const InetAddress *>(remoteAddress)),packetData,packetLength);
  137. return ZT_RESULT_OK;
  138. }
  139. ZT_ResultCode Node::processVirtualNetworkFrame(
  140. void *tptr,
  141. int64_t now,
  142. uint64_t nwid,
  143. uint64_t sourceMac,
  144. uint64_t destMac,
  145. unsigned int etherType,
  146. unsigned int vlanId,
  147. const void *frameData,
  148. unsigned int frameLength,
  149. volatile int64_t *nextBackgroundTaskDeadline)
  150. {
  151. _now = now;
  152. SharedPtr<Network> nw(this->network(nwid));
  153. if (nw) {
  154. RR->sw->onLocalEthernet(tptr,nw,MAC(sourceMac),MAC(destMac),etherType,vlanId,frameData,frameLength);
  155. return ZT_RESULT_OK;
  156. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  157. }
  158. struct _processBackgroundTasks_ping_eachRoot
  159. {
  160. Hashtable< void *,bool > roots;
  161. int64_t now;
  162. void *tPtr;
  163. bool online;
  164. inline void operator()(const Root &root,const SharedPtr<Peer> &peer)
  165. {
  166. unsigned int v4SendCount = 0,v6SendCount = 0;
  167. peer->ping(tPtr,now,v4SendCount,v6SendCount);
  168. const InetAddress *contactAddrs[2];
  169. unsigned int contactAddrCount = 0;
  170. if (v4SendCount == 0) {
  171. if (*(contactAddrs[contactAddrCount] = &(root.pickPhysical(AF_INET))))
  172. ++contactAddrCount;
  173. }
  174. if (v6SendCount == 0) {
  175. if (*(contactAddrs[contactAddrCount] = &(root.pickPhysical(AF_INET6))))
  176. ++contactAddrCount;
  177. }
  178. for(unsigned int i=0;i<contactAddrCount;++i)
  179. peer->sendHELLO(tPtr,-1,*contactAddrs[i],now);
  180. if (!online)
  181. online = ((now - peer->lastReceive()) <= ((ZT_PEER_PING_PERIOD * 2) + 5000));
  182. roots.set((void *)peer.ptr(),true);
  183. }
  184. };
  185. struct _processBackgroundTasks_ping_eachPeer
  186. {
  187. int64_t now;
  188. void *tPtr;
  189. Hashtable< void *,bool > *roots;
  190. inline void operator()(const SharedPtr<Peer> &peer)
  191. {
  192. if (!roots->contains((void *)peer.ptr())) {
  193. unsigned int v4SendCount = 0,v6SendCount = 0;
  194. peer->ping(tPtr,now,v4SendCount,v6SendCount);
  195. }
  196. }
  197. };
  198. ZT_ResultCode Node::processBackgroundTasks(void *tptr,int64_t now,volatile int64_t *nextBackgroundTaskDeadline)
  199. {
  200. _now = now;
  201. Mutex::Lock bl(_backgroundTasksLock);
  202. // Initialize these on first call so these things happen just a few seconds after
  203. // startup, since right at startup things are likely to not be ready to communicate
  204. // at all yet.
  205. if (_lastNetworkHousekeepingRun <= 0) _lastNetworkHousekeepingRun = now - (ZT_NETWORK_HOUSEKEEPING_PERIOD / 3);
  206. if (_lastHousekeepingRun <= 0) _lastHousekeepingRun = now;
  207. if ((now - _lastPing) >= ZT_PEER_PING_PERIOD) {
  208. _lastPing = now;
  209. try {
  210. _processBackgroundTasks_ping_eachRoot rf;
  211. rf.now = now;
  212. rf.tPtr = tptr;
  213. rf.online = false;
  214. RR->topology->eachRoot(rf);
  215. _processBackgroundTasks_ping_eachPeer pf;
  216. pf.now = now;
  217. pf.tPtr = tptr;
  218. pf.roots = &rf.roots;
  219. RR->topology->eachPeer(pf);
  220. if (rf.online != _online) {
  221. _online = rf.online;
  222. postEvent(tptr,_online ? ZT_EVENT_ONLINE : ZT_EVENT_OFFLINE);
  223. }
  224. } catch ( ... ) {
  225. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  226. }
  227. }
  228. if ((now - _lastNetworkHousekeepingRun) >= ZT_NETWORK_HOUSEKEEPING_PERIOD) {
  229. _lastHousekeepingRun = now;
  230. {
  231. Mutex::Lock l(_networks_m);
  232. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(_networks);
  233. uint64_t *nwid = (uint64_t *)0;
  234. SharedPtr<Network> *network = (SharedPtr<Network> *)0;
  235. while (i.next(nwid,network)) {
  236. (*network)->doPeriodicTasks(tptr,now);
  237. }
  238. }
  239. RR->t->updateMemoizedSettings();
  240. }
  241. if ((now - _lastHousekeepingRun) >= ZT_HOUSEKEEPING_PERIOD) {
  242. _lastHousekeepingRun = now;
  243. try {
  244. // Clean up any old local controller auth memoizations. This is an
  245. // optimization for network controllers to know whether to accept
  246. // or trust nodes without doing an extra cert check.
  247. {
  248. _localControllerAuthorizations_m.lock();
  249. Hashtable< _LocalControllerAuth,int64_t >::Iterator i(_localControllerAuthorizations);
  250. _LocalControllerAuth *k = (_LocalControllerAuth *)0;
  251. int64_t *v = (int64_t *)0;
  252. while (i.next(k,v)) {
  253. if ((*v - now) > (ZT_NETWORK_AUTOCONF_DELAY * 3)) {
  254. _localControllerAuthorizations.erase(*k);
  255. }
  256. }
  257. _localControllerAuthorizations_m.unlock();
  258. }
  259. RR->topology->doPeriodicTasks(now);
  260. RR->sa->clean(now);
  261. RR->mc->clean(now);
  262. } catch ( ... ) {
  263. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  264. }
  265. }
  266. try {
  267. *nextBackgroundTaskDeadline = now + (int64_t)std::max(std::min((unsigned long)ZT_MAX_TIMER_TASK_INTERVAL,RR->sw->doTimerTasks(tptr,now)),(unsigned long)ZT_MIN_TIMER_TASK_INTERVAL);
  268. } catch ( ... ) {
  269. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  270. }
  271. return ZT_RESULT_OK;
  272. }
  273. ZT_ResultCode Node::join(uint64_t nwid,void *uptr,void *tptr)
  274. {
  275. Mutex::Lock _l(_networks_m);
  276. SharedPtr<Network> &nw = _networks[nwid];
  277. if (!nw)
  278. nw = SharedPtr<Network>(new Network(RR,tptr,nwid,uptr,(const NetworkConfig *)0));
  279. return ZT_RESULT_OK;
  280. }
  281. ZT_ResultCode Node::leave(uint64_t nwid,void **uptr,void *tptr)
  282. {
  283. ZT_VirtualNetworkConfig ctmp;
  284. void **nUserPtr = (void **)0;
  285. {
  286. Mutex::Lock _l(_networks_m);
  287. SharedPtr<Network> *nw = _networks.get(nwid);
  288. RR->sw->removeNetworkQoSControlBlock(nwid);
  289. if (!nw)
  290. return ZT_RESULT_OK;
  291. if (uptr)
  292. *uptr = (*nw)->userPtr();
  293. (*nw)->externalConfig(&ctmp);
  294. (*nw)->destroy();
  295. nUserPtr = (*nw)->userPtr();
  296. }
  297. if (nUserPtr)
  298. RR->node->configureVirtualNetworkPort(tptr,nwid,nUserPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
  299. {
  300. Mutex::Lock _l(_networks_m);
  301. _networks.erase(nwid);
  302. }
  303. uint64_t tmp[2];
  304. tmp[0] = nwid; tmp[1] = 0;
  305. RR->node->stateObjectDelete(tptr,ZT_STATE_OBJECT_NETWORK_CONFIG,tmp);
  306. return ZT_RESULT_OK;
  307. }
  308. ZT_ResultCode Node::multicastSubscribe(void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  309. {
  310. SharedPtr<Network> nw(this->network(nwid));
  311. if (nw) {
  312. nw->multicastSubscribe(tptr,MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  313. return ZT_RESULT_OK;
  314. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  315. }
  316. ZT_ResultCode Node::multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  317. {
  318. SharedPtr<Network> nw(this->network(nwid));
  319. if (nw) {
  320. nw->multicastUnsubscribe(MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  321. return ZT_RESULT_OK;
  322. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  323. }
  324. uint64_t Node::address() const
  325. {
  326. return RR->identity.address().toInt();
  327. }
  328. void Node::status(ZT_NodeStatus *status) const
  329. {
  330. status->address = RR->identity.address().toInt();
  331. status->publicIdentity = RR->publicIdentityStr;
  332. status->secretIdentity = RR->secretIdentityStr;
  333. status->online = _online ? 1 : 0;
  334. }
  335. struct _sortPeerPtrsByAddress { inline bool operator()(const SharedPtr<Peer> &a,const SharedPtr<Peer> &b) const { return (a->address() < b->address()); } };
  336. ZT_PeerList *Node::peers() const
  337. {
  338. std::vector< SharedPtr<Peer> > peers;
  339. RR->topology->getAllPeers(peers);
  340. std::sort(peers.begin(),peers.end(),_sortPeerPtrsByAddress());
  341. char *buf = (char *)::malloc(sizeof(ZT_PeerList) + (sizeof(ZT_Peer) * peers.size()));
  342. if (!buf)
  343. return (ZT_PeerList *)0;
  344. ZT_PeerList *pl = (ZT_PeerList *)buf;
  345. pl->peers = (ZT_Peer *)(buf + sizeof(ZT_PeerList));
  346. pl->peerCount = 0;
  347. for(std::vector< SharedPtr<Peer> >::iterator pi(peers.begin());pi!=peers.end();++pi) {
  348. ZT_Peer *p = &(pl->peers[pl->peerCount++]);
  349. p->address = (*pi)->address().toInt();
  350. p->hadAggregateLink = 0;
  351. if ((*pi)->remoteVersionKnown()) {
  352. p->versionMajor = (*pi)->remoteVersionMajor();
  353. p->versionMinor = (*pi)->remoteVersionMinor();
  354. p->versionRev = (*pi)->remoteVersionRevision();
  355. } else {
  356. p->versionMajor = -1;
  357. p->versionMinor = -1;
  358. p->versionRev = -1;
  359. }
  360. p->latency = (*pi)->latency(_now);
  361. if (p->latency >= 0xffff)
  362. p->latency = -1;
  363. p->role = RR->topology->isRoot((*pi)->identity()) ? ZT_PEER_ROLE_PLANET : ZT_PEER_ROLE_LEAF;
  364. std::vector< SharedPtr<Path> > paths((*pi)->paths(_now));
  365. SharedPtr<Path> bestp((*pi)->getAppropriatePath(_now,false));
  366. p->hadAggregateLink |= (*pi)->hasAggregateLink();
  367. p->pathCount = 0;
  368. for(std::vector< SharedPtr<Path> >::iterator path(paths.begin());path!=paths.end();++path) {
  369. memcpy(&(p->paths[p->pathCount].address),&((*path)->address()),sizeof(struct sockaddr_storage));
  370. p->paths[p->pathCount].lastSend = (*path)->lastOut();
  371. p->paths[p->pathCount].lastReceive = (*path)->lastIn();
  372. p->paths[p->pathCount].trustedPathId = RR->topology->getOutboundPathTrust((*path)->address());
  373. p->paths[p->pathCount].expired = 0;
  374. p->paths[p->pathCount].preferred = ((*path) == bestp) ? 1 : 0;
  375. p->paths[p->pathCount].latency = (float)(*path)->latency();
  376. p->paths[p->pathCount].packetDelayVariance = (*path)->packetDelayVariance();
  377. p->paths[p->pathCount].throughputDisturbCoeff = (*path)->throughputDisturbanceCoefficient();
  378. p->paths[p->pathCount].packetErrorRatio = (*path)->packetErrorRatio();
  379. p->paths[p->pathCount].packetLossRatio = (*path)->packetLossRatio();
  380. p->paths[p->pathCount].stability = (*path)->lastComputedStability();
  381. p->paths[p->pathCount].throughput = (*path)->meanThroughput();
  382. p->paths[p->pathCount].maxThroughput = (*path)->maxLifetimeThroughput();
  383. p->paths[p->pathCount].allocation = (float)(*path)->allocation() / (float)255;
  384. p->paths[p->pathCount].ifname = (*path)->getName();
  385. ++p->pathCount;
  386. }
  387. }
  388. return pl;
  389. }
  390. ZT_VirtualNetworkConfig *Node::networkConfig(uint64_t nwid) const
  391. {
  392. Mutex::Lock _l(_networks_m);
  393. const SharedPtr<Network> *nw = _networks.get(nwid);
  394. if (nw) {
  395. ZT_VirtualNetworkConfig *nc = (ZT_VirtualNetworkConfig *)::malloc(sizeof(ZT_VirtualNetworkConfig));
  396. (*nw)->externalConfig(nc);
  397. return nc;
  398. }
  399. return (ZT_VirtualNetworkConfig *)0;
  400. }
  401. ZT_VirtualNetworkList *Node::networks() const
  402. {
  403. Mutex::Lock _l(_networks_m);
  404. char *buf = (char *)::malloc(sizeof(ZT_VirtualNetworkList) + (sizeof(ZT_VirtualNetworkConfig) * _networks.size()));
  405. if (!buf)
  406. return (ZT_VirtualNetworkList *)0;
  407. ZT_VirtualNetworkList *nl = (ZT_VirtualNetworkList *)buf;
  408. nl->networks = (ZT_VirtualNetworkConfig *)(buf + sizeof(ZT_VirtualNetworkList));
  409. nl->networkCount = 0;
  410. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(*const_cast< Hashtable< uint64_t,SharedPtr<Network> > *>(&_networks));
  411. uint64_t *k = (uint64_t *)0;
  412. SharedPtr<Network> *v = (SharedPtr<Network> *)0;
  413. while (i.next(k,v))
  414. (*v)->externalConfig(&(nl->networks[nl->networkCount++]));
  415. return nl;
  416. }
  417. void Node::freeQueryResult(void *qr)
  418. {
  419. if (qr)
  420. ::free(qr);
  421. }
  422. int Node::addLocalInterfaceAddress(const struct sockaddr_storage *addr)
  423. {
  424. if (Path::isAddressValidForPath(*(reinterpret_cast<const InetAddress *>(addr)))) {
  425. Mutex::Lock _l(_localInterfaceAddresses_m);
  426. if (std::find(_localInterfaceAddresses.begin(),_localInterfaceAddresses.end(),*(reinterpret_cast<const InetAddress *>(addr))) == _localInterfaceAddresses.end()) {
  427. _localInterfaceAddresses.push_back(*(reinterpret_cast<const InetAddress *>(addr)));
  428. return 1;
  429. }
  430. }
  431. return 0;
  432. }
  433. void Node::clearLocalInterfaceAddresses()
  434. {
  435. Mutex::Lock _l(_localInterfaceAddresses_m);
  436. _localInterfaceAddresses.clear();
  437. }
  438. int Node::sendUserMessage(void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len)
  439. {
  440. try {
  441. if (RR->identity.address().toInt() != dest) {
  442. Packet outp(Address(dest),RR->identity.address(),Packet::VERB_USER_MESSAGE);
  443. outp.append(typeId);
  444. outp.append(data,len);
  445. outp.compress();
  446. RR->sw->send(tptr,outp,true);
  447. return 1;
  448. }
  449. } catch ( ... ) {}
  450. return 0;
  451. }
  452. void Node::setController(void *networkControllerInstance)
  453. {
  454. RR->localNetworkController = reinterpret_cast<NetworkController *>(networkControllerInstance);
  455. if (networkControllerInstance)
  456. RR->localNetworkController->init(RR->identity,this);
  457. }
  458. /****************************************************************************/
  459. /* Node methods used only within node/ */
  460. /****************************************************************************/
  461. bool Node::shouldUsePathForZeroTierTraffic(void *tPtr,const Address &ztaddr,const int64_t localSocket,const InetAddress &remoteAddress)
  462. {
  463. if (!Path::isAddressValidForPath(remoteAddress))
  464. return false;
  465. {
  466. Mutex::Lock _l(_networks_m);
  467. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(_networks);
  468. uint64_t *k = (uint64_t *)0;
  469. SharedPtr<Network> *v = (SharedPtr<Network> *)0;
  470. while (i.next(k,v)) {
  471. if ((*v)->hasConfig()) {
  472. for(unsigned int k=0;k<(*v)->config().staticIpCount;++k) {
  473. if ((*v)->config().staticIps[k].containsAddress(remoteAddress))
  474. return false;
  475. }
  476. }
  477. }
  478. }
  479. return ( (_cb.pathCheckFunction) ? (_cb.pathCheckFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,ztaddr.toInt(),localSocket,reinterpret_cast<const struct sockaddr_storage *>(&remoteAddress)) != 0) : true);
  480. }
  481. ZT_ResultCode Node::setPhysicalPathConfiguration(const struct sockaddr_storage *pathNetwork, const ZT_PhysicalPathConfiguration *pathConfig)
  482. {
  483. RR->topology->setPhysicalPathConfiguration(pathNetwork,pathConfig);
  484. return ZT_RESULT_OK;
  485. }
  486. void Node::ncSendConfig(uint64_t nwid,uint64_t requestPacketId,const Address &destination,const NetworkConfig &nc,bool sendLegacyFormatConfig)
  487. {
  488. _localControllerAuthorizations_m.lock();
  489. _localControllerAuthorizations[_LocalControllerAuth(nwid,destination)] = now();
  490. _localControllerAuthorizations_m.unlock();
  491. if (destination == RR->identity.address()) {
  492. SharedPtr<Network> n(network(nwid));
  493. if (!n) return;
  494. n->setConfiguration((void *)0,nc,true);
  495. } else {
  496. ScopedPtr< Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> > dconf(new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>());
  497. if (nc.toDictionary(*dconf,sendLegacyFormatConfig)) {
  498. uint64_t configUpdateId = Utils::random();
  499. if (!configUpdateId) ++configUpdateId;
  500. const unsigned int totalSize = dconf->sizeBytes();
  501. unsigned int chunkIndex = 0;
  502. while (chunkIndex < totalSize) {
  503. const unsigned int chunkLen = std::min(totalSize - chunkIndex,(unsigned int)(ZT_PROTO_MAX_PACKET_LENGTH - (ZT_PACKET_IDX_PAYLOAD + 256)));
  504. Packet outp(destination,RR->identity.address(),(requestPacketId) ? Packet::VERB_OK : Packet::VERB_NETWORK_CONFIG);
  505. if (requestPacketId) {
  506. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  507. outp.append(requestPacketId);
  508. }
  509. const unsigned int sigStart = outp.size();
  510. outp.append(nwid);
  511. outp.append((uint16_t)chunkLen);
  512. outp.append((const void *)(dconf->data() + chunkIndex),chunkLen);
  513. outp.append((uint8_t)0); // no flags
  514. outp.append((uint64_t)configUpdateId);
  515. outp.append((uint32_t)totalSize);
  516. outp.append((uint32_t)chunkIndex);
  517. uint8_t sig[256];
  518. const unsigned int siglen = RR->identity.sign(reinterpret_cast<const uint8_t *>(outp.data()) + sigStart,outp.size() - sigStart,sig,sizeof(sig));
  519. outp.append((uint8_t)1);
  520. outp.append((uint16_t)siglen);
  521. outp.append(sig,siglen);
  522. outp.compress();
  523. RR->sw->send((void *)0,outp,true);
  524. chunkIndex += chunkLen;
  525. }
  526. }
  527. }
  528. }
  529. void Node::ncSendRevocation(const Address &destination,const Revocation &rev)
  530. {
  531. if (destination == RR->identity.address()) {
  532. SharedPtr<Network> n(network(rev.networkId()));
  533. if (!n) return;
  534. n->addCredential((void *)0,RR->identity.address(),rev);
  535. } else {
  536. Packet outp(destination,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  537. outp.append((uint8_t)0x00);
  538. outp.append((uint16_t)0);
  539. outp.append((uint16_t)0);
  540. outp.append((uint16_t)1);
  541. rev.serialize(outp);
  542. outp.append((uint16_t)0);
  543. RR->sw->send((void *)0,outp,true);
  544. }
  545. }
  546. void Node::ncSendError(uint64_t nwid,uint64_t requestPacketId,const Address &destination,NetworkController::ErrorCode errorCode)
  547. {
  548. if (destination == RR->identity.address()) {
  549. SharedPtr<Network> n(network(nwid));
  550. if (!n) return;
  551. switch(errorCode) {
  552. case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  553. case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  554. n->setNotFound();
  555. break;
  556. case NetworkController::NC_ERROR_ACCESS_DENIED:
  557. n->setAccessDenied();
  558. break;
  559. default: break;
  560. }
  561. } else if (requestPacketId) {
  562. Packet outp(destination,RR->identity.address(),Packet::VERB_ERROR);
  563. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  564. outp.append(requestPacketId);
  565. switch(errorCode) {
  566. //case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  567. //case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  568. default:
  569. outp.append((unsigned char)Packet::ERROR_OBJ_NOT_FOUND);
  570. break;
  571. case NetworkController::NC_ERROR_ACCESS_DENIED:
  572. outp.append((unsigned char)Packet::ERROR_NETWORK_ACCESS_DENIED_);
  573. break;
  574. }
  575. outp.append(nwid);
  576. RR->sw->send((void *)0,outp,true);
  577. } // else we can't send an ERROR() in response to nothing, so discard
  578. }
  579. } // namespace ZeroTier
  580. /****************************************************************************/
  581. /* CAPI bindings */
  582. /****************************************************************************/
  583. extern "C" {
  584. enum ZT_ResultCode ZT_Node_new(ZT_Node **node,void *uptr,void *tptr,const struct ZT_Node_Callbacks *callbacks,int64_t now)
  585. {
  586. *node = (ZT_Node *)0;
  587. try {
  588. *node = reinterpret_cast<ZT_Node *>(new ZeroTier::Node(uptr,tptr,callbacks,now));
  589. return ZT_RESULT_OK;
  590. } catch (std::bad_alloc &exc) {
  591. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  592. } catch (std::runtime_error &exc) {
  593. return ZT_RESULT_FATAL_ERROR_DATA_STORE_FAILED;
  594. } catch ( ... ) {
  595. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  596. }
  597. }
  598. void ZT_Node_delete(ZT_Node *node)
  599. {
  600. try {
  601. delete (reinterpret_cast<ZeroTier::Node *>(node));
  602. } catch ( ... ) {}
  603. }
  604. enum ZT_ResultCode ZT_Node_processWirePacket(
  605. ZT_Node *node,
  606. void *tptr,
  607. int64_t now,
  608. int64_t localSocket,
  609. const struct sockaddr_storage *remoteAddress,
  610. const void *packetData,
  611. unsigned int packetLength,
  612. volatile int64_t *nextBackgroundTaskDeadline)
  613. {
  614. try {
  615. return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(tptr,now,localSocket,remoteAddress,packetData,packetLength,nextBackgroundTaskDeadline);
  616. } catch (std::bad_alloc &exc) {
  617. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  618. } catch ( ... ) {
  619. return ZT_RESULT_OK; // "OK" since invalid packets are simply dropped, but the system is still up
  620. }
  621. }
  622. enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame(
  623. ZT_Node *node,
  624. void *tptr,
  625. int64_t now,
  626. uint64_t nwid,
  627. uint64_t sourceMac,
  628. uint64_t destMac,
  629. unsigned int etherType,
  630. unsigned int vlanId,
  631. const void *frameData,
  632. unsigned int frameLength,
  633. volatile int64_t *nextBackgroundTaskDeadline)
  634. {
  635. try {
  636. return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(tptr,now,nwid,sourceMac,destMac,etherType,vlanId,frameData,frameLength,nextBackgroundTaskDeadline);
  637. } catch (std::bad_alloc &exc) {
  638. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  639. } catch ( ... ) {
  640. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  641. }
  642. }
  643. enum ZT_ResultCode ZT_Node_processBackgroundTasks(ZT_Node *node,void *tptr,int64_t now,volatile int64_t *nextBackgroundTaskDeadline)
  644. {
  645. try {
  646. return reinterpret_cast<ZeroTier::Node *>(node)->processBackgroundTasks(tptr,now,nextBackgroundTaskDeadline);
  647. } catch (std::bad_alloc &exc) {
  648. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  649. } catch ( ... ) {
  650. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  651. }
  652. }
  653. enum ZT_ResultCode ZT_Node_join(ZT_Node *node,uint64_t nwid,void *uptr,void *tptr)
  654. {
  655. try {
  656. return reinterpret_cast<ZeroTier::Node *>(node)->join(nwid,uptr,tptr);
  657. } catch (std::bad_alloc &exc) {
  658. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  659. } catch ( ... ) {
  660. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  661. }
  662. }
  663. enum ZT_ResultCode ZT_Node_leave(ZT_Node *node,uint64_t nwid,void **uptr,void *tptr)
  664. {
  665. try {
  666. return reinterpret_cast<ZeroTier::Node *>(node)->leave(nwid,uptr,tptr);
  667. } catch (std::bad_alloc &exc) {
  668. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  669. } catch ( ... ) {
  670. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  671. }
  672. }
  673. enum ZT_ResultCode ZT_Node_multicastSubscribe(ZT_Node *node,void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  674. {
  675. try {
  676. return reinterpret_cast<ZeroTier::Node *>(node)->multicastSubscribe(tptr,nwid,multicastGroup,multicastAdi);
  677. } catch (std::bad_alloc &exc) {
  678. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  679. } catch ( ... ) {
  680. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  681. }
  682. }
  683. enum ZT_ResultCode ZT_Node_multicastUnsubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  684. {
  685. try {
  686. return reinterpret_cast<ZeroTier::Node *>(node)->multicastUnsubscribe(nwid,multicastGroup,multicastAdi);
  687. } catch (std::bad_alloc &exc) {
  688. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  689. } catch ( ... ) {
  690. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  691. }
  692. }
  693. uint64_t ZT_Node_address(ZT_Node *node)
  694. {
  695. return reinterpret_cast<ZeroTier::Node *>(node)->address();
  696. }
  697. void ZT_Node_status(ZT_Node *node,ZT_NodeStatus *status)
  698. {
  699. try {
  700. reinterpret_cast<ZeroTier::Node *>(node)->status(status);
  701. } catch ( ... ) {}
  702. }
  703. ZT_PeerList *ZT_Node_peers(ZT_Node *node)
  704. {
  705. try {
  706. return reinterpret_cast<ZeroTier::Node *>(node)->peers();
  707. } catch ( ... ) {
  708. return (ZT_PeerList *)0;
  709. }
  710. }
  711. ZT_VirtualNetworkConfig *ZT_Node_networkConfig(ZT_Node *node,uint64_t nwid)
  712. {
  713. try {
  714. return reinterpret_cast<ZeroTier::Node *>(node)->networkConfig(nwid);
  715. } catch ( ... ) {
  716. return (ZT_VirtualNetworkConfig *)0;
  717. }
  718. }
  719. ZT_VirtualNetworkList *ZT_Node_networks(ZT_Node *node)
  720. {
  721. try {
  722. return reinterpret_cast<ZeroTier::Node *>(node)->networks();
  723. } catch ( ... ) {
  724. return (ZT_VirtualNetworkList *)0;
  725. }
  726. }
  727. void ZT_Node_freeQueryResult(ZT_Node *node,void *qr)
  728. {
  729. try {
  730. reinterpret_cast<ZeroTier::Node *>(node)->freeQueryResult(qr);
  731. } catch ( ... ) {}
  732. }
  733. int ZT_Node_addLocalInterfaceAddress(ZT_Node *node,const struct sockaddr_storage *addr)
  734. {
  735. try {
  736. return reinterpret_cast<ZeroTier::Node *>(node)->addLocalInterfaceAddress(addr);
  737. } catch ( ... ) {
  738. return 0;
  739. }
  740. }
  741. void ZT_Node_clearLocalInterfaceAddresses(ZT_Node *node)
  742. {
  743. try {
  744. reinterpret_cast<ZeroTier::Node *>(node)->clearLocalInterfaceAddresses();
  745. } catch ( ... ) {}
  746. }
  747. int ZT_Node_sendUserMessage(ZT_Node *node,void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len)
  748. {
  749. try {
  750. return reinterpret_cast<ZeroTier::Node *>(node)->sendUserMessage(tptr,dest,typeId,data,len);
  751. } catch ( ... ) {
  752. return 0;
  753. }
  754. }
  755. void ZT_Node_setController(ZT_Node *node,void *networkControllerInstance)
  756. {
  757. try {
  758. reinterpret_cast<ZeroTier::Node *>(node)->setController(networkControllerInstance);
  759. } catch ( ... ) {}
  760. }
  761. enum ZT_ResultCode ZT_Node_setPhysicalPathConfiguration(ZT_Node *node,const struct sockaddr_storage *pathNetwork,const ZT_PhysicalPathConfiguration *pathConfig)
  762. {
  763. try {
  764. return reinterpret_cast<ZeroTier::Node *>(node)->setPhysicalPathConfiguration(pathNetwork,pathConfig);
  765. } catch ( ... ) {
  766. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  767. }
  768. }
  769. void ZT_version(int *major,int *minor,int *revision)
  770. {
  771. if (major) *major = ZEROTIER_ONE_VERSION_MAJOR;
  772. if (minor) *minor = ZEROTIER_ONE_VERSION_MINOR;
  773. if (revision) *revision = ZEROTIER_ONE_VERSION_REVISION;
  774. }
  775. } // extern "C"