Peer.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  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. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include "../version.h"
  28. #include "Constants.hpp"
  29. #include "Peer.hpp"
  30. #include "Node.hpp"
  31. #include "Switch.hpp"
  32. #include "Network.hpp"
  33. #include "SelfAwareness.hpp"
  34. #include "Cluster.hpp"
  35. #include "Packet.hpp"
  36. #include <algorithm>
  37. #define ZT_PEER_PATH_SORT_INTERVAL 5000
  38. namespace ZeroTier {
  39. // Used to send varying values for NAT keepalive
  40. static uint32_t _natKeepaliveBuf = 0;
  41. Peer::Peer(const RuntimeEnvironment *renv,const Identity &myIdentity,const Identity &peerIdentity) :
  42. RR(renv),
  43. _lastUsed(0),
  44. _lastReceive(0),
  45. _lastUnicastFrame(0),
  46. _lastMulticastFrame(0),
  47. _lastAnnouncedTo(0),
  48. _lastDirectPathPushSent(0),
  49. _lastDirectPathPushReceive(0),
  50. _lastPathSort(0),
  51. _vProto(0),
  52. _vMajor(0),
  53. _vMinor(0),
  54. _vRevision(0),
  55. _id(peerIdentity),
  56. _numPaths(0),
  57. _latency(0),
  58. _directPathPushCutoffCount(0),
  59. _networkComs(4),
  60. _lastPushedComs(4)
  61. {
  62. if (!myIdentity.agree(peerIdentity,_key,ZT_PEER_SECRET_KEY_LENGTH))
  63. throw std::runtime_error("new peer identity key agreement failed");
  64. }
  65. void Peer::received(
  66. const InetAddress &localAddr,
  67. const InetAddress &remoteAddr,
  68. unsigned int hops,
  69. uint64_t packetId,
  70. Packet::Verb verb,
  71. uint64_t inRePacketId,
  72. Packet::Verb inReVerb)
  73. {
  74. #ifdef ZT_ENABLE_CLUSTER
  75. bool suboptimalPath = false;
  76. if ((RR->cluster)&&(hops == 0)) {
  77. // Note: findBetterEndpoint() is first since we still want to check
  78. // for a better endpoint even if we don't actually send a redirect.
  79. InetAddress redirectTo;
  80. if ( (RR->cluster->findBetterEndpoint(redirectTo,_id.address(),remoteAddr,false)) && (verb != Packet::VERB_OK)&&(verb != Packet::VERB_ERROR)&&(verb != Packet::VERB_RENDEZVOUS)&&(verb != Packet::VERB_PUSH_DIRECT_PATHS) ) {
  81. if (_vProto >= 5) {
  82. // For newer peers we can send a more idiomatic verb: PUSH_DIRECT_PATHS.
  83. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_PUSH_DIRECT_PATHS);
  84. outp.append((uint16_t)1); // count == 1
  85. outp.append((uint8_t)0); // no flags
  86. outp.append((uint16_t)0); // no extensions
  87. if (redirectTo.ss_family == AF_INET) {
  88. outp.append((uint8_t)4);
  89. outp.append((uint8_t)6);
  90. outp.append(redirectTo.rawIpData(),4);
  91. } else {
  92. outp.append((uint8_t)6);
  93. outp.append((uint8_t)18);
  94. outp.append(redirectTo.rawIpData(),16);
  95. }
  96. outp.append((uint16_t)redirectTo.port());
  97. outp.armor(_key,true);
  98. RR->node->putPacket(localAddr,remoteAddr,outp.data(),outp.size());
  99. } else {
  100. // For older peers we use RENDEZVOUS to coax them into contacting us elsewhere.
  101. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_RENDEZVOUS);
  102. outp.append((uint8_t)0); // no flags
  103. RR->identity.address().appendTo(outp);
  104. outp.append((uint16_t)redirectTo.port());
  105. if (redirectTo.ss_family == AF_INET) {
  106. outp.append((uint8_t)4);
  107. outp.append(redirectTo.rawIpData(),4);
  108. } else {
  109. outp.append((uint8_t)16);
  110. outp.append(redirectTo.rawIpData(),16);
  111. }
  112. outp.armor(_key,true);
  113. RR->node->putPacket(localAddr,remoteAddr,outp.data(),outp.size());
  114. }
  115. suboptimalPath = true;
  116. }
  117. }
  118. #endif
  119. const uint64_t now = RR->node->now();
  120. _lastReceive = now;
  121. if ((verb == Packet::VERB_FRAME)||(verb == Packet::VERB_EXT_FRAME))
  122. _lastUnicastFrame = now;
  123. else if (verb == Packet::VERB_MULTICAST_FRAME)
  124. _lastMulticastFrame = now;
  125. if (hops == 0) {
  126. bool pathIsConfirmed = false;
  127. unsigned int np = _numPaths;
  128. for(unsigned int p=0;p<np;++p) {
  129. if ((_paths[p].address() == remoteAddr)&&(_paths[p].localAddress() == localAddr)) {
  130. _paths[p].received(now);
  131. #ifdef ZT_ENABLE_CLUSTER
  132. _paths[p].setClusterSuboptimal(suboptimalPath);
  133. #endif
  134. pathIsConfirmed = true;
  135. break;
  136. }
  137. }
  138. if ((!pathIsConfirmed)&&(RR->node->shouldUsePathForZeroTierTraffic(localAddr,remoteAddr))) {
  139. if (verb == Packet::VERB_OK) {
  140. Path *slot = (Path *)0;
  141. if (np < ZT_MAX_PEER_NETWORK_PATHS) {
  142. slot = &(_paths[np++]);
  143. } else {
  144. uint64_t slotLRmin = 0xffffffffffffffffULL;
  145. for(unsigned int p=0;p<ZT_MAX_PEER_NETWORK_PATHS;++p) {
  146. if (!_paths[p].active(now)) {
  147. slot = &(_paths[p]);
  148. break;
  149. } else if (_paths[p].lastReceived() <= slotLRmin) {
  150. slotLRmin = _paths[p].lastReceived();
  151. slot = &(_paths[p]);
  152. }
  153. }
  154. }
  155. if (slot) {
  156. *slot = Path(localAddr,remoteAddr);
  157. slot->received(now);
  158. #ifdef ZT_ENABLE_CLUSTER
  159. slot->setClusterSuboptimal(suboptimalPath);
  160. #endif
  161. _numPaths = np;
  162. }
  163. #ifdef ZT_ENABLE_CLUSTER
  164. if (RR->cluster)
  165. RR->cluster->broadcastHavePeer(_id);
  166. #endif
  167. } else {
  168. TRACE("got %s via unknown path %s(%s), confirming...",Packet::verbString(verb),_id.address().toString().c_str(),remoteAddr.toString().c_str());
  169. if ( (_vProto >= 5) && ( !((_vMajor == 1)&&(_vMinor == 1)&&(_vRevision == 0)) ) ) {
  170. // 1.1.1 and newer nodes support ECHO, which is smaller -- but 1.1.0 has a bug so use HELLO there too
  171. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_ECHO);
  172. outp.armor(_key,true);
  173. RR->node->putPacket(localAddr,remoteAddr,outp.data(),outp.size());
  174. } else {
  175. sendHELLO(localAddr,remoteAddr,now);
  176. }
  177. }
  178. }
  179. }
  180. if ((now - _lastAnnouncedTo) >= ((ZT_MULTICAST_LIKE_EXPIRE / 2) - 1000)) {
  181. _lastAnnouncedTo = now;
  182. const std::vector< SharedPtr<Network> > networks(RR->node->allNetworks());
  183. for(std::vector< SharedPtr<Network> >::const_iterator n(networks.begin());n!=networks.end();++n)
  184. (*n)->tryAnnounceMulticastGroupsTo(SharedPtr<Peer>(this));
  185. }
  186. }
  187. void Peer::sendHELLO(const InetAddress &localAddr,const InetAddress &atAddress,uint64_t now,unsigned int ttl)
  188. {
  189. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_HELLO);
  190. outp.append((unsigned char)ZT_PROTO_VERSION);
  191. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  192. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  193. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  194. outp.append(now);
  195. RR->identity.serialize(outp,false);
  196. atAddress.serialize(outp);
  197. outp.append((uint64_t)RR->topology->worldId());
  198. outp.append((uint64_t)RR->topology->worldTimestamp());
  199. outp.armor(_key,false); // HELLO is sent in the clear
  200. RR->node->putPacket(localAddr,atAddress,outp.data(),outp.size(),ttl);
  201. }
  202. bool Peer::doPingAndKeepalive(uint64_t now,int inetAddressFamily)
  203. {
  204. Path *p = (Path *)0;
  205. if (inetAddressFamily != 0) {
  206. p = _getBestPath(now,inetAddressFamily);
  207. } else {
  208. p = _getBestPath(now);
  209. }
  210. if (p) {
  211. if ((now - p->lastReceived()) >= ZT_PEER_DIRECT_PING_DELAY) {
  212. //TRACE("PING %s(%s) after %llums/%llums send/receive inactivity",_id.address().toString().c_str(),p->address().toString().c_str(),now - p->lastSend(),now - p->lastReceived());
  213. sendHELLO(p->localAddress(),p->address(),now);
  214. p->sent(now);
  215. p->pinged(now);
  216. } else if ( ((now - std::max(p->lastSend(),p->lastKeepalive())) >= ZT_NAT_KEEPALIVE_DELAY) && (!p->reliable()) ) {
  217. //TRACE("NAT keepalive %s(%s) after %llums/%llums send/receive inactivity",_id.address().toString().c_str(),p->address().toString().c_str(),now - p->lastSend(),now - p->lastReceived());
  218. _natKeepaliveBuf += (uint32_t)((now * 0x9e3779b1) >> 1); // tumble this around to send constantly varying (meaningless) payloads
  219. RR->node->putPacket(p->localAddress(),p->address(),&_natKeepaliveBuf,sizeof(_natKeepaliveBuf));
  220. p->sentKeepalive(now);
  221. } else {
  222. //TRACE("no PING or NAT keepalive: addr==%s reliable==%d %llums/%llums send/receive inactivity",p->address().toString().c_str(),(int)p->reliable(),now - p->lastSend(),now - p->lastReceived());
  223. }
  224. return true;
  225. }
  226. return false;
  227. }
  228. void Peer::pushDirectPaths(Path *path,uint64_t now,bool force)
  229. {
  230. #ifdef ZT_ENABLE_CLUSTER
  231. // Cluster mode disables normal PUSH_DIRECT_PATHS in favor of cluster-based peer redirection
  232. if (RR->cluster)
  233. return;
  234. #endif
  235. if (((now - _lastDirectPathPushSent) >= ZT_DIRECT_PATH_PUSH_INTERVAL)||(force)) {
  236. _lastDirectPathPushSent = now;
  237. std::vector<InetAddress> dps(RR->node->directPaths());
  238. if (dps.empty())
  239. return;
  240. #ifdef ZT_TRACE
  241. {
  242. std::string ps;
  243. for(std::vector<InetAddress>::const_iterator p(dps.begin());p!=dps.end();++p) {
  244. if (ps.length() > 0)
  245. ps.push_back(',');
  246. ps.append(p->toString());
  247. }
  248. TRACE("pushing %u direct paths to %s: %s",(unsigned int)dps.size(),_id.address().toString().c_str(),ps.c_str());
  249. }
  250. #endif
  251. std::vector<InetAddress>::const_iterator p(dps.begin());
  252. while (p != dps.end()) {
  253. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_PUSH_DIRECT_PATHS);
  254. outp.addSize(2); // leave room for count
  255. unsigned int count = 0;
  256. while ((p != dps.end())&&((outp.size() + 24) < ZT_PROTO_MAX_PACKET_LENGTH)) {
  257. uint8_t addressType = 4;
  258. switch(p->ss_family) {
  259. case AF_INET:
  260. break;
  261. case AF_INET6:
  262. addressType = 6;
  263. break;
  264. default: // we currently only push IP addresses
  265. ++p;
  266. continue;
  267. }
  268. outp.append((uint8_t)0); // no flags
  269. outp.append((uint16_t)0); // no extensions
  270. outp.append(addressType);
  271. outp.append((uint8_t)((addressType == 4) ? 6 : 18));
  272. outp.append(p->rawIpData(),((addressType == 4) ? 4 : 16));
  273. outp.append((uint16_t)p->port());
  274. ++count;
  275. ++p;
  276. }
  277. if (count) {
  278. outp.setAt(ZT_PACKET_IDX_PAYLOAD,(uint16_t)count);
  279. outp.armor(_key,true);
  280. path->send(RR,outp.data(),outp.size(),now);
  281. }
  282. }
  283. }
  284. }
  285. bool Peer::resetWithinScope(InetAddress::IpScope scope,uint64_t now)
  286. {
  287. unsigned int np = _numPaths;
  288. unsigned int x = 0;
  289. unsigned int y = 0;
  290. while (x < np) {
  291. if (_paths[x].address().ipScope() == scope) {
  292. // Resetting a path means sending a HELLO and then forgetting it. If we
  293. // get OK(HELLO) then it will be re-learned.
  294. sendHELLO(_paths[x].localAddress(),_paths[x].address(),now);
  295. } else {
  296. _paths[y++] = _paths[x];
  297. }
  298. ++x;
  299. }
  300. _numPaths = y;
  301. return (y < np);
  302. }
  303. void Peer::getBestActiveAddresses(uint64_t now,InetAddress &v4,InetAddress &v6) const
  304. {
  305. uint64_t bestV4 = 0,bestV6 = 0;
  306. for(unsigned int p=0,np=_numPaths;p<np;++p) {
  307. if (_paths[p].active(now)) {
  308. uint64_t lr = _paths[p].lastReceived();
  309. if (lr) {
  310. if (_paths[p].address().isV4()) {
  311. if (lr >= bestV4) {
  312. bestV4 = lr;
  313. v4 = _paths[p].address();
  314. }
  315. } else if (_paths[p].address().isV6()) {
  316. if (lr >= bestV6) {
  317. bestV6 = lr;
  318. v6 = _paths[p].address();
  319. }
  320. }
  321. }
  322. }
  323. }
  324. }
  325. bool Peer::networkMembershipCertificatesAgree(uint64_t nwid,const CertificateOfMembership &com) const
  326. {
  327. Mutex::Lock _l(_networkComs_m);
  328. const _NetworkCom *ourCom = _networkComs.get(nwid);
  329. if (ourCom)
  330. return ourCom->com.agreesWith(com);
  331. return false;
  332. }
  333. bool Peer::validateAndSetNetworkMembershipCertificate(uint64_t nwid,const CertificateOfMembership &com)
  334. {
  335. // Sanity checks
  336. if ((!com)||(com.issuedTo() != _id.address()))
  337. return false;
  338. // Return true if we already have this *exact* COM
  339. {
  340. Mutex::Lock _l(_networkComs_m);
  341. _NetworkCom *ourCom = _networkComs.get(nwid);
  342. if ((ourCom)&&(ourCom->com == com))
  343. return true;
  344. }
  345. // Check signature, log and return if cert is invalid
  346. if (com.signedBy() != Network::controllerFor(nwid)) {
  347. TRACE("rejected network membership certificate for %.16llx signed by %s: signer not a controller of this network",(unsigned long long)_id,com.signedBy().toString().c_str());
  348. return false; // invalid signer
  349. }
  350. if (com.signedBy() == RR->identity.address()) {
  351. // We are the controller: RR->identity.address() == controller() == cert.signedBy()
  352. // So, verify that we signed th cert ourself
  353. if (!com.verify(RR->identity)) {
  354. TRACE("rejected network membership certificate for %.16llx self signed by %s: signature check failed",(unsigned long long)_id,com.signedBy().toString().c_str());
  355. return false; // invalid signature
  356. }
  357. } else {
  358. SharedPtr<Peer> signer(RR->topology->getPeer(com.signedBy()));
  359. if (!signer) {
  360. // This would be rather odd, since this is our controller... could happen
  361. // if we get packets before we've gotten config.
  362. RR->sw->requestWhois(com.signedBy());
  363. return false; // signer unknown
  364. }
  365. if (!com.verify(signer->identity())) {
  366. TRACE("rejected network membership certificate for %.16llx signed by %s: signature check failed",(unsigned long long)_id,com.signedBy().toString().c_str());
  367. return false; // invalid signature
  368. }
  369. }
  370. // If we made it past all those checks, add or update cert in our cert info store
  371. {
  372. Mutex::Lock _l(_networkComs_m);
  373. _networkComs.set(nwid,_NetworkCom(RR->node->now(),com));
  374. }
  375. return true;
  376. }
  377. bool Peer::needsOurNetworkMembershipCertificate(uint64_t nwid,uint64_t now,bool updateLastPushedTime)
  378. {
  379. Mutex::Lock _l(_networkComs_m);
  380. uint64_t &lastPushed = _lastPushedComs[nwid];
  381. const uint64_t tmp = lastPushed;
  382. if (updateLastPushedTime)
  383. lastPushed = now;
  384. return ((now - tmp) >= (ZT_NETWORK_AUTOCONF_DELAY / 2));
  385. }
  386. void Peer::clean(uint64_t now)
  387. {
  388. {
  389. unsigned int np = _numPaths;
  390. unsigned int x = 0;
  391. unsigned int y = 0;
  392. while (x < np) {
  393. if (_paths[x].active(now))
  394. _paths[y++] = _paths[x];
  395. ++x;
  396. }
  397. _numPaths = y;
  398. }
  399. {
  400. Mutex::Lock _l(_networkComs_m);
  401. {
  402. uint64_t *k = (uint64_t *)0;
  403. _NetworkCom *v = (_NetworkCom *)0;
  404. Hashtable< uint64_t,_NetworkCom >::Iterator i(_networkComs);
  405. while (i.next(k,v)) {
  406. if ( (!RR->node->belongsToNetwork(*k)) && ((now - v->ts) >= ZT_PEER_NETWORK_COM_EXPIRATION) )
  407. _networkComs.erase(*k);
  408. }
  409. }
  410. {
  411. uint64_t *k = (uint64_t *)0;
  412. uint64_t *v = (uint64_t *)0;
  413. Hashtable< uint64_t,uint64_t >::Iterator i(_lastPushedComs);
  414. while (i.next(k,v)) {
  415. if ((now - *v) > (ZT_NETWORK_AUTOCONF_DELAY * 2))
  416. _lastPushedComs.erase(*k);
  417. }
  418. }
  419. }
  420. }
  421. bool Peer::_checkPath(Path &p,const uint64_t now)
  422. {
  423. if (!p.active(now))
  424. return false;
  425. /* Dead path detection: if we have sent something to this peer and have not
  426. * yet received a reply, double check this path. The majority of outbound
  427. * packets including Ethernet frames do generate some kind of reply either
  428. * immediately or at some point in the near future. This will occasionally
  429. * (every NO_ANSWER_TIMEOUT ms) check paths unnecessarily if traffic that
  430. * does not generate a response is being sent such as multicast announcements
  431. * or frames belonging to unidirectional UDP protocols, but the cost is very
  432. * tiny and the benefit in reliability is very large. This takes care of many
  433. * failure modes including crap NATs that forget links and spurious changes
  434. * to physical network topology that cannot be otherwise detected.
  435. *
  436. * Each time we do this we increment a probation counter in the path. This
  437. * counter is reset on any packet receive over this path. If it reaches the
  438. * MAX_PROBATION threshold the path is considred dead. */
  439. if (
  440. (p.lastSend() > p.lastReceived()) &&
  441. ((p.lastSend() - p.lastReceived()) >= ZT_PEER_DEAD_PATH_DETECTION_NO_ANSWER_TIMEOUT) &&
  442. ((now - p.lastPing()) >= ZT_PEER_DEAD_PATH_DETECTION_NO_ANSWER_TIMEOUT) &&
  443. (!RR->topology->amRoot())
  444. ) {
  445. TRACE("%s(%s) does not seem to be answering in a timely manner, checking if dead (probation == %u)",_id.address().toString().c_str(),p.address().toString().c_str(),p.probation());
  446. if ( (_vProto >= 5) && ( !((_vMajor == 1)&&(_vMinor == 1)&&(_vRevision == 0)) ) ) {
  447. // 1.1.1 and newer nodes support ECHO, which is smaller -- but 1.1.0 has a bug so use HELLO there too
  448. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_ECHO);
  449. outp.armor(_key,true);
  450. p.send(RR,outp.data(),outp.size(),now);
  451. p.pinged(now);
  452. } else {
  453. sendHELLO(p.localAddress(),p.address(),now);
  454. p.sent(now);
  455. p.pinged(now);
  456. }
  457. p.increaseProbation();
  458. }
  459. return true;
  460. }
  461. Path *Peer::_getBestPath(const uint64_t now)
  462. {
  463. Path *bestPath = (Path *)0;
  464. uint64_t bestPathScore = 0;
  465. for(unsigned int i=0;i<_numPaths;++i) {
  466. const uint64_t score = _paths[i].score();
  467. if ((score >= bestPathScore)&&(_checkPath(_paths[i],now))) {
  468. bestPathScore = score;
  469. bestPath = &(_paths[i]);
  470. }
  471. }
  472. return bestPath;
  473. }
  474. Path *Peer::_getBestPath(const uint64_t now,int inetAddressFamily)
  475. {
  476. Path *bestPath = (Path *)0;
  477. uint64_t bestPathScore = 0;
  478. for(unsigned int i=0;i<_numPaths;++i) {
  479. const uint64_t score = _paths[i].score();
  480. if (((int)_paths[i].address().ss_family == inetAddressFamily)&&(score >= bestPathScore)&&(_checkPath(_paths[i],now))) {
  481. bestPathScore = score;
  482. bestPath = &(_paths[i]);
  483. }
  484. }
  485. return bestPath;
  486. }
  487. } // namespace ZeroTier