Node.cpp 28 KB

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