Peer.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2017 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 "../version.h"
  27. #include "Constants.hpp"
  28. #include "Peer.hpp"
  29. #include "Node.hpp"
  30. #include "Switch.hpp"
  31. #include "Network.hpp"
  32. #include "SelfAwareness.hpp"
  33. #include "Packet.hpp"
  34. namespace ZeroTier {
  35. Peer::Peer(const RuntimeEnvironment *renv,const Identity &myIdentity,const Identity &peerIdentity) :
  36. RR(renv),
  37. _lastWroteState(0),
  38. _lastReceivedStateTimestamp(0),
  39. _lastReceive(0),
  40. _lastNontrivialReceive(0),
  41. _lastTriedMemorizedPath(0),
  42. _lastDirectPathPushSent(0),
  43. _lastDirectPathPushReceive(0),
  44. _lastCredentialRequestSent(0),
  45. _lastWhoisRequestReceived(0),
  46. _lastEchoRequestReceived(0),
  47. _lastComRequestReceived(0),
  48. _lastComRequestSent(0),
  49. _lastCredentialsReceived(0),
  50. _lastTrustEstablishedPacketReceived(0),
  51. _vProto(0),
  52. _vMajor(0),
  53. _vMinor(0),
  54. _vRevision(0),
  55. _id(peerIdentity),
  56. _latency(0),
  57. _directPathPushCutoffCount(0),
  58. _credentialsCutoffCount(0)
  59. {
  60. if (!myIdentity.agree(peerIdentity,_key,ZT_PEER_SECRET_KEY_LENGTH))
  61. throw std::runtime_error("new peer identity key agreement failed");
  62. }
  63. void Peer::received(
  64. void *tPtr,
  65. const SharedPtr<Path> &path,
  66. const unsigned int hops,
  67. const uint64_t packetId,
  68. const Packet::Verb verb,
  69. const uint64_t inRePacketId,
  70. const Packet::Verb inReVerb,
  71. const bool trustEstablished)
  72. {
  73. const uint64_t now = RR->node->now();
  74. /*
  75. #ifdef ZT_ENABLE_CLUSTER
  76. bool isClusterSuboptimalPath = false;
  77. if ((RR->cluster)&&(hops == 0)) {
  78. // Note: findBetterEndpoint() is first since we still want to check
  79. // for a better endpoint even if we don't actually send a redirect.
  80. InetAddress redirectTo;
  81. if ( (verb != Packet::VERB_OK) && (verb != Packet::VERB_ERROR) && (verb != Packet::VERB_RENDEZVOUS) && (verb != Packet::VERB_PUSH_DIRECT_PATHS) && (RR->cluster->findBetterEndpoint(redirectTo,_id.address(),path->address(),false)) ) {
  82. if (_vProto >= 5) {
  83. // For newer peers we can send a more idiomatic verb: PUSH_DIRECT_PATHS.
  84. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_PUSH_DIRECT_PATHS);
  85. outp.append((uint16_t)1); // count == 1
  86. outp.append((uint8_t)ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT); // flags: cluster redirect
  87. outp.append((uint16_t)0); // no extensions
  88. if (redirectTo.ss_family == AF_INET) {
  89. outp.append((uint8_t)4);
  90. outp.append((uint8_t)6);
  91. outp.append(redirectTo.rawIpData(),4);
  92. } else {
  93. outp.append((uint8_t)6);
  94. outp.append((uint8_t)18);
  95. outp.append(redirectTo.rawIpData(),16);
  96. }
  97. outp.append((uint16_t)redirectTo.port());
  98. outp.armor(_key,true,path->nextOutgoingCounter());
  99. path->send(RR,tPtr,outp.data(),outp.size(),now);
  100. } else {
  101. // For older peers we use RENDEZVOUS to coax them into contacting us elsewhere.
  102. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_RENDEZVOUS);
  103. outp.append((uint8_t)0); // no flags
  104. RR->identity.address().appendTo(outp);
  105. outp.append((uint16_t)redirectTo.port());
  106. if (redirectTo.ss_family == AF_INET) {
  107. outp.append((uint8_t)4);
  108. outp.append(redirectTo.rawIpData(),4);
  109. } else {
  110. outp.append((uint8_t)16);
  111. outp.append(redirectTo.rawIpData(),16);
  112. }
  113. outp.armor(_key,true,path->nextOutgoingCounter());
  114. path->send(RR,tPtr,outp.data(),outp.size(),now);
  115. }
  116. isClusterSuboptimalPath = true;
  117. }
  118. }
  119. #endif
  120. */
  121. _lastReceive = now;
  122. switch (verb) {
  123. case Packet::VERB_FRAME:
  124. case Packet::VERB_EXT_FRAME:
  125. case Packet::VERB_NETWORK_CONFIG_REQUEST:
  126. case Packet::VERB_NETWORK_CONFIG:
  127. case Packet::VERB_MULTICAST_FRAME:
  128. _lastNontrivialReceive = now;
  129. break;
  130. default: break;
  131. }
  132. if (trustEstablished) {
  133. _lastTrustEstablishedPacketReceived = now;
  134. path->trustedPacketReceived(now);
  135. }
  136. if (_vProto >= 9)
  137. path->updateLinkQuality((unsigned int)(packetId & 7));
  138. if (hops == 0) {
  139. bool pathAlreadyKnown = false;
  140. bool newPathLearned = false;
  141. {
  142. Mutex::Lock _l(_paths_m);
  143. if ((path->address().ss_family == AF_INET)&&(_v4Path.p)) {
  144. const struct sockaddr_in *const r = reinterpret_cast<const struct sockaddr_in *>(&(path->address()));
  145. const struct sockaddr_in *const l = reinterpret_cast<const struct sockaddr_in *>(&(_v4Path.p->address()));
  146. const struct sockaddr_in *const rl = reinterpret_cast<const struct sockaddr_in *>(&(path->localAddress()));
  147. const struct sockaddr_in *const ll = reinterpret_cast<const struct sockaddr_in *>(&(_v4Path.p->localAddress()));
  148. if ((r->sin_addr.s_addr == l->sin_addr.s_addr)&&(r->sin_port == l->sin_port)&&(rl->sin_addr.s_addr == ll->sin_addr.s_addr)&&(rl->sin_port == ll->sin_port)) {
  149. _v4Path.lr = now;
  150. pathAlreadyKnown = true;
  151. }
  152. } else if ((path->address().ss_family == AF_INET6)&&(_v6Path.p)) {
  153. const struct sockaddr_in6 *const r = reinterpret_cast<const struct sockaddr_in6 *>(&(path->address()));
  154. const struct sockaddr_in6 *const l = reinterpret_cast<const struct sockaddr_in6 *>(&(_v6Path.p->address()));
  155. const struct sockaddr_in6 *const rl = reinterpret_cast<const struct sockaddr_in6 *>(&(path->localAddress()));
  156. const struct sockaddr_in6 *const ll = reinterpret_cast<const struct sockaddr_in6 *>(&(_v6Path.p->localAddress()));
  157. if ((!memcmp(r->sin6_addr.s6_addr,l->sin6_addr.s6_addr,16))&&(r->sin6_port == l->sin6_port)&&(!memcmp(rl->sin6_addr.s6_addr,ll->sin6_addr.s6_addr,16))&&(rl->sin6_port == ll->sin6_port)) {
  158. _v6Path.lr = now;
  159. pathAlreadyKnown = true;
  160. }
  161. }
  162. }
  163. if ( (!pathAlreadyKnown) && (RR->node->shouldUsePathForZeroTierTraffic(tPtr,_id.address(),path->localAddress(),path->address())) ) {
  164. Mutex::Lock _l(_paths_m);
  165. _PeerPath *potentialNewPeerPath = (_PeerPath *)0;
  166. if (path->address().ss_family == AF_INET) {
  167. if ( (!_v4Path.p) || (!_v4Path.p->alive(now)) || (path->preferenceRank() >= _v4Path.p->preferenceRank()) ) {
  168. potentialNewPeerPath = &_v4Path;
  169. }
  170. } else if (path->address().ss_family == AF_INET6) {
  171. if ( (!_v6Path.p) || (!_v6Path.p->alive(now)) || (path->preferenceRank() >= _v6Path.p->preferenceRank()) ) {
  172. potentialNewPeerPath = &_v6Path;
  173. }
  174. }
  175. if (potentialNewPeerPath) {
  176. if (verb == Packet::VERB_OK) {
  177. potentialNewPeerPath->lr = now;
  178. potentialNewPeerPath->p = path;
  179. newPathLearned = true;
  180. } else {
  181. TRACE("got %s via unknown path %s(%s), confirming...",Packet::verbString(verb),_id.address().toString().c_str(),path->address().toString().c_str());
  182. attemptToContactAt(tPtr,path->localAddress(),path->address(),now,true,path->nextOutgoingCounter());
  183. path->sent(now);
  184. }
  185. }
  186. }
  187. if (newPathLearned)
  188. writeState(tPtr,now);
  189. } else if (this->trustEstablished(now)) {
  190. // Send PUSH_DIRECT_PATHS if hops>0 (relayed) and we have a trust relationship (common network membership)
  191. if ((now - _lastDirectPathPushSent) >= ZT_DIRECT_PATH_PUSH_INTERVAL) {
  192. _lastDirectPathPushSent = now;
  193. std::vector<InetAddress> pathsToPush;
  194. std::vector<InetAddress> dps(RR->node->directPaths());
  195. for(std::vector<InetAddress>::const_iterator i(dps.begin());i!=dps.end();++i)
  196. pathsToPush.push_back(*i);
  197. std::vector<InetAddress> sym(RR->sa->getSymmetricNatPredictions());
  198. for(unsigned long i=0,added=0;i<sym.size();++i) {
  199. InetAddress tmp(sym[(unsigned long)RR->node->prng() % sym.size()]);
  200. if (std::find(pathsToPush.begin(),pathsToPush.end(),tmp) == pathsToPush.end()) {
  201. pathsToPush.push_back(tmp);
  202. if (++added >= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY)
  203. break;
  204. }
  205. }
  206. if (pathsToPush.size() > 0) {
  207. #ifdef ZT_TRACE
  208. std::string ps;
  209. for(std::vector<InetAddress>::const_iterator p(pathsToPush.begin());p!=pathsToPush.end();++p) {
  210. if (ps.length() > 0)
  211. ps.push_back(',');
  212. ps.append(p->toString());
  213. }
  214. TRACE("pushing %u direct paths to %s: %s",(unsigned int)pathsToPush.size(),_id.address().toString().c_str(),ps.c_str());
  215. #endif
  216. std::vector<InetAddress>::const_iterator p(pathsToPush.begin());
  217. while (p != pathsToPush.end()) {
  218. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_PUSH_DIRECT_PATHS);
  219. outp.addSize(2); // leave room for count
  220. unsigned int count = 0;
  221. while ((p != pathsToPush.end())&&((outp.size() + 24) < 1200)) {
  222. uint8_t addressType = 4;
  223. switch(p->ss_family) {
  224. case AF_INET:
  225. break;
  226. case AF_INET6:
  227. addressType = 6;
  228. break;
  229. default: // we currently only push IP addresses
  230. ++p;
  231. continue;
  232. }
  233. outp.append((uint8_t)0); // no flags
  234. outp.append((uint16_t)0); // no extensions
  235. outp.append(addressType);
  236. outp.append((uint8_t)((addressType == 4) ? 6 : 18));
  237. outp.append(p->rawIpData(),((addressType == 4) ? 4 : 16));
  238. outp.append((uint16_t)p->port());
  239. ++count;
  240. ++p;
  241. }
  242. if (count) {
  243. outp.setAt(ZT_PACKET_IDX_PAYLOAD,(uint16_t)count);
  244. outp.armor(_key,true,path->nextOutgoingCounter());
  245. path->send(RR,tPtr,outp.data(),outp.size(),now);
  246. }
  247. }
  248. }
  249. }
  250. }
  251. }
  252. bool Peer::sendDirect(void *tPtr,const void *data,unsigned int len,uint64_t now,bool force)
  253. {
  254. Mutex::Lock _l(_paths_m);
  255. uint64_t v6lr = 0;
  256. if ( ((now - _v6Path.lr) < ZT_PEER_PATH_EXPIRATION) && (_v6Path.p) )
  257. v6lr = _v6Path.p->lastIn();
  258. uint64_t v4lr = 0;
  259. if ( ((now - _v4Path.lr) < ZT_PEER_PATH_EXPIRATION) && (_v4Path.p) )
  260. v4lr = _v4Path.p->lastIn();
  261. if ( (v6lr > v4lr) && ((now - v6lr) < ZT_PATH_ALIVE_TIMEOUT) ) {
  262. return _v6Path.p->send(RR,tPtr,data,len,now);
  263. } else if ((now - v4lr) < ZT_PATH_ALIVE_TIMEOUT) {
  264. return _v4Path.p->send(RR,tPtr,data,len,now);
  265. } else if (force) {
  266. if (v6lr > v4lr) {
  267. return _v6Path.p->send(RR,tPtr,data,len,now);
  268. } else if (v4lr) {
  269. return _v4Path.p->send(RR,tPtr,data,len,now);
  270. }
  271. }
  272. return false;
  273. }
  274. SharedPtr<Path> Peer::getBestPath(uint64_t now,bool includeExpired)
  275. {
  276. Mutex::Lock _l(_paths_m);
  277. uint64_t v6lr = 0;
  278. if ( ( includeExpired || ((now - _v6Path.lr) < ZT_PEER_PATH_EXPIRATION) ) && (_v6Path.p) )
  279. v6lr = _v6Path.p->lastIn();
  280. uint64_t v4lr = 0;
  281. if ( ( includeExpired || ((now - _v4Path.lr) < ZT_PEER_PATH_EXPIRATION) ) && (_v4Path.p) )
  282. v4lr = _v4Path.p->lastIn();
  283. if (v6lr > v4lr) {
  284. return _v6Path.p;
  285. } else if (v4lr) {
  286. return _v4Path.p;
  287. }
  288. return SharedPtr<Path>();
  289. }
  290. void Peer::sendHELLO(void *tPtr,const InetAddress &localAddr,const InetAddress &atAddress,uint64_t now,unsigned int counter)
  291. {
  292. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_HELLO);
  293. outp.append((unsigned char)ZT_PROTO_VERSION);
  294. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  295. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  296. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  297. outp.append(now);
  298. RR->identity.serialize(outp,false);
  299. atAddress.serialize(outp);
  300. outp.append((uint64_t)RR->topology->planetWorldId());
  301. outp.append((uint64_t)RR->topology->planetWorldTimestamp());
  302. const unsigned int startCryptedPortionAt = outp.size();
  303. std::vector<World> moons(RR->topology->moons());
  304. std::vector<uint64_t> moonsWanted(RR->topology->moonsWanted());
  305. outp.append((uint16_t)(moons.size() + moonsWanted.size()));
  306. for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
  307. outp.append((uint8_t)m->type());
  308. outp.append((uint64_t)m->id());
  309. outp.append((uint64_t)m->timestamp());
  310. }
  311. for(std::vector<uint64_t>::const_iterator m(moonsWanted.begin());m!=moonsWanted.end();++m) {
  312. outp.append((uint8_t)World::TYPE_MOON);
  313. outp.append(*m);
  314. outp.append((uint64_t)0);
  315. }
  316. const unsigned int corSizeAt = outp.size();
  317. outp.addSize(2);
  318. RR->topology->appendCertificateOfRepresentation(outp);
  319. outp.setAt(corSizeAt,(uint16_t)(outp.size() - (corSizeAt + 2)));
  320. outp.cryptField(_key,startCryptedPortionAt,outp.size() - startCryptedPortionAt);
  321. RR->node->expectReplyTo(outp.packetId());
  322. if (atAddress) {
  323. outp.armor(_key,false,counter); // false == don't encrypt full payload, but add MAC
  324. RR->node->putPacket(tPtr,localAddr,atAddress,outp.data(),outp.size());
  325. } else {
  326. RR->sw->send(tPtr,outp,false); // false == don't encrypt full payload, but add MAC
  327. }
  328. }
  329. void Peer::attemptToContactAt(void *tPtr,const InetAddress &localAddr,const InetAddress &atAddress,uint64_t now,bool sendFullHello,unsigned int counter)
  330. {
  331. if ( (!sendFullHello) && (_vProto >= 5) && (!((_vMajor == 1)&&(_vMinor == 1)&&(_vRevision == 0))) ) {
  332. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_ECHO);
  333. RR->node->expectReplyTo(outp.packetId());
  334. outp.armor(_key,true,counter);
  335. RR->node->putPacket(tPtr,localAddr,atAddress,outp.data(),outp.size());
  336. } else {
  337. sendHELLO(tPtr,localAddr,atAddress,now,counter);
  338. }
  339. }
  340. void Peer::tryMemorizedPath(void *tPtr,uint64_t now)
  341. {
  342. if ((now - _lastTriedMemorizedPath) >= ZT_TRY_MEMORIZED_PATH_INTERVAL) {
  343. _lastTriedMemorizedPath = now;
  344. InetAddress mp;
  345. if (RR->node->externalPathLookup(tPtr,_id.address(),-1,mp))
  346. attemptToContactAt(tPtr,InetAddress(),mp,now,true,0);
  347. }
  348. }
  349. bool Peer::doPingAndKeepalive(void *tPtr,uint64_t now,int inetAddressFamily)
  350. {
  351. Mutex::Lock _l(_paths_m);
  352. if (inetAddressFamily < 0) {
  353. uint64_t v6lr = 0;
  354. if ( ((now - _v6Path.lr) < ZT_PEER_PATH_EXPIRATION) && (_v6Path.p) )
  355. v6lr = _v6Path.p->lastIn();
  356. uint64_t v4lr = 0;
  357. if ( ((now - _v4Path.lr) < ZT_PEER_PATH_EXPIRATION) && (_v4Path.p) )
  358. v4lr = _v4Path.p->lastIn();
  359. if (v6lr > v4lr) {
  360. if ( ((now - _v6Path.lr) >= ZT_PEER_PING_PERIOD) || (_v6Path.p->needsHeartbeat(now)) ) {
  361. attemptToContactAt(tPtr,_v6Path.p->localAddress(),_v6Path.p->address(),now,false,_v6Path.p->nextOutgoingCounter());
  362. _v6Path.p->sent(now);
  363. return true;
  364. }
  365. } else if (v4lr) {
  366. if ( ((now - _v4Path.lr) >= ZT_PEER_PING_PERIOD) || (_v4Path.p->needsHeartbeat(now)) ) {
  367. attemptToContactAt(tPtr,_v4Path.p->localAddress(),_v4Path.p->address(),now,false,_v4Path.p->nextOutgoingCounter());
  368. _v4Path.p->sent(now);
  369. return true;
  370. }
  371. }
  372. } else {
  373. if ( (inetAddressFamily == AF_INET) && ((now - _v4Path.lr) < ZT_PEER_PATH_EXPIRATION) ) {
  374. if ( ((now - _v4Path.lr) >= ZT_PEER_PING_PERIOD) || (_v4Path.p->needsHeartbeat(now)) ) {
  375. attemptToContactAt(tPtr,_v4Path.p->localAddress(),_v4Path.p->address(),now,false,_v4Path.p->nextOutgoingCounter());
  376. _v4Path.p->sent(now);
  377. return true;
  378. }
  379. } else if ( (inetAddressFamily == AF_INET6) && ((now - _v6Path.lr) < ZT_PEER_PATH_EXPIRATION) ) {
  380. if ( ((now - _v6Path.lr) >= ZT_PEER_PING_PERIOD) || (_v6Path.p->needsHeartbeat(now)) ) {
  381. attemptToContactAt(tPtr,_v6Path.p->localAddress(),_v6Path.p->address(),now,false,_v6Path.p->nextOutgoingCounter());
  382. _v6Path.p->sent(now);
  383. return true;
  384. }
  385. }
  386. }
  387. return false;
  388. }
  389. void Peer::writeState(void *tPtr,const uint64_t now)
  390. {
  391. try {
  392. Buffer<sizeof(Peer) + 32 + (sizeof(Path) * 2)> b;
  393. b.append((uint8_t)1); // version
  394. b.append(now);
  395. _id.serialize(b);
  396. {
  397. Mutex::Lock _l(_paths_m);
  398. unsigned int count = 0;
  399. if (_v4Path.lr)
  400. ++count;
  401. if (_v6Path.lr)
  402. ++count;
  403. b.append((uint8_t)count);
  404. if (_v4Path.lr) {
  405. b.append(_v4Path.lr);
  406. b.append(_v4Path.p->lastOut());
  407. b.append(_v4Path.p->lastIn());
  408. b.append(_v4Path.p->lastTrustEstablishedPacketReceived());
  409. b.append((uint16_t)_v4Path.p->distance());
  410. _v4Path.p->address().serialize(b);
  411. _v4Path.p->localAddress().serialize(b);
  412. }
  413. if (_v6Path.lr) {
  414. b.append(_v6Path.lr);
  415. b.append(_v6Path.p->lastOut());
  416. b.append(_v6Path.p->lastIn());
  417. b.append(_v6Path.p->lastTrustEstablishedPacketReceived());
  418. b.append((uint16_t)_v6Path.p->distance());
  419. _v6Path.p->address().serialize(b);
  420. _v6Path.p->localAddress().serialize(b);
  421. }
  422. }
  423. b.append(_lastReceive);
  424. b.append(_lastNontrivialReceive);
  425. b.append(_lastTriedMemorizedPath);
  426. b.append(_lastDirectPathPushSent);
  427. b.append(_lastDirectPathPushReceive);
  428. b.append(_lastCredentialRequestSent);
  429. b.append(_lastWhoisRequestReceived);
  430. b.append(_lastEchoRequestReceived);
  431. b.append(_lastComRequestReceived);
  432. b.append(_lastComRequestSent);
  433. b.append(_lastCredentialsReceived);
  434. b.append(_lastTrustEstablishedPacketReceived);
  435. b.append(_vProto);
  436. b.append(_vMajor);
  437. b.append(_vMinor);
  438. b.append(_vRevision);
  439. b.append((uint16_t)0); // length of additional fields
  440. uint64_t tmp[2];
  441. tmp[0] = _id.address().toInt(); tmp[1] = 0;
  442. RR->node->stateObjectPut(tPtr,ZT_STATE_OBJECT_PEER_STATE,tmp,b.data(),b.size());
  443. _lastWroteState = now;
  444. } catch ( ... ) {} // sanity check, should not be possible
  445. }
  446. bool Peer::applyStateUpdate(const void *data,unsigned int len)
  447. {
  448. try {
  449. Buffer<sizeof(Peer) + 32 + (sizeof(Path) * 2)> b(data,len);
  450. unsigned int ptr = 0;
  451. if (b[ptr++] != 1)
  452. return false;
  453. const uint64_t ts = b.at<uint64_t>(ptr); ptr += 8;
  454. if (ts <= _lastReceivedStateTimestamp)
  455. return false;
  456. const unsigned int pathCount = (unsigned int)b[ptr++];
  457. {
  458. Mutex::Lock _l(_paths_m);
  459. for(unsigned int i=0;i<pathCount;++i) {
  460. const uint64_t lr = b.at<uint64_t>(ptr); ptr += 8;
  461. const uint64_t lastOut = b.at<uint64_t>(ptr); ptr += 8;
  462. const uint64_t lastIn = b.at<uint64_t>(ptr); ptr += 8;
  463. const uint64_t lastTrustEstablishedPacketReceived = b.at<uint64_t>(ptr); ptr += 8;
  464. const unsigned int distance = b.at<uint16_t>(ptr); ptr += 2;
  465. InetAddress addr,localAddr;
  466. ptr += addr.deserialize(b,ptr);
  467. ptr += localAddr.deserialize(b,ptr);
  468. if (addr.ss_family == localAddr.ss_family) {
  469. _PeerPath *p = (_PeerPath *)0;
  470. switch(addr.ss_family) {
  471. case AF_INET: p = &_v4Path; break;
  472. case AF_INET6: p = &_v6Path; break;
  473. }
  474. if (p) {
  475. if ( ((p->p->address() != addr)||(p->p->localAddress() != localAddr)) && (p->p->distance() > distance) )
  476. p->p = RR->topology->getPath(localAddr,addr);
  477. p->lr = lr;
  478. p->p->updateFromRemoteState(lastOut,lastIn,lastTrustEstablishedPacketReceived);
  479. }
  480. }
  481. }
  482. }
  483. _lastReceive = std::max(_lastReceive,b.at<uint64_t>(ptr)); ptr += 8;
  484. _lastNontrivialReceive = std::max(_lastNontrivialReceive,b.at<uint64_t>(ptr)); ptr += 8;
  485. _lastTriedMemorizedPath = std::max(_lastTriedMemorizedPath,b.at<uint64_t>(ptr)); ptr += 8;
  486. _lastDirectPathPushSent = std::max(_lastDirectPathPushSent,b.at<uint64_t>(ptr)); ptr += 8;
  487. _lastDirectPathPushReceive = std::max(_lastDirectPathPushReceive,b.at<uint64_t>(ptr)); ptr += 8;
  488. _lastCredentialRequestSent = std::max(_lastCredentialRequestSent,b.at<uint64_t>(ptr)); ptr += 8;
  489. _lastWhoisRequestReceived = std::max(_lastWhoisRequestReceived,b.at<uint64_t>(ptr)); ptr += 8;
  490. _lastEchoRequestReceived = std::max(_lastEchoRequestReceived,b.at<uint64_t>(ptr)); ptr += 8;
  491. _lastComRequestReceived = std::max(_lastComRequestReceived,b.at<uint64_t>(ptr)); ptr += 8;
  492. _lastComRequestSent = std::max(_lastComRequestSent,b.at<uint64_t>(ptr)); ptr += 8;
  493. _lastCredentialsReceived = std::max(_lastCredentialsReceived,b.at<uint64_t>(ptr)); ptr += 8;
  494. _lastTrustEstablishedPacketReceived = std::max(_lastTrustEstablishedPacketReceived,b.at<uint64_t>(ptr)); ptr += 8;
  495. _vProto = b.at<uint16_t>(ptr); ptr += 2;
  496. _vMajor = b.at<uint16_t>(ptr); ptr += 2;
  497. _vMinor = b.at<uint16_t>(ptr); ptr += 2;
  498. _vRevision = b.at<uint16_t>(ptr); ptr += 2;
  499. _lastReceivedStateTimestamp = ts;
  500. return true;
  501. } catch ( ... ) {} // ignore invalid state updates
  502. return false;
  503. }
  504. } // namespace ZeroTier