Node.cpp 27 KB

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