Peer.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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 "AntiRecursion.hpp"
  34. #include "SelfAwareness.hpp"
  35. #include "Cluster.hpp"
  36. #include "Packet.hpp"
  37. #include <algorithm>
  38. #define ZT_PEER_PATH_SORT_INTERVAL 5000
  39. namespace ZeroTier {
  40. // Used to send varying values for NAT keepalive
  41. static uint32_t _natKeepaliveBuf = 0;
  42. Peer::Peer(const Identity &myIdentity,const Identity &peerIdentity)
  43. throw(std::runtime_error) :
  44. _lastUsed(0),
  45. _lastReceive(0),
  46. _lastUnicastFrame(0),
  47. _lastMulticastFrame(0),
  48. _lastAnnouncedTo(0),
  49. _lastPathConfirmationSent(0),
  50. _lastDirectPathPushSent(0),
  51. _lastDirectPathPushReceive(0),
  52. _lastPathSort(0),
  53. _vProto(0),
  54. _vMajor(0),
  55. _vMinor(0),
  56. _vRevision(0),
  57. _id(peerIdentity),
  58. _numPaths(0),
  59. _latency(0),
  60. _directPathPushCutoffCount(0),
  61. _networkComs(4),
  62. _lastPushedComs(4)
  63. {
  64. if (!myIdentity.agree(peerIdentity,_key,ZT_PEER_SECRET_KEY_LENGTH))
  65. throw std::runtime_error("new peer identity key agreement failed");
  66. }
  67. void Peer::received(
  68. const RuntimeEnvironment *RR,
  69. const InetAddress &localAddr,
  70. const InetAddress &remoteAddr,
  71. unsigned int hops,
  72. uint64_t packetId,
  73. Packet::Verb verb,
  74. uint64_t inRePacketId,
  75. Packet::Verb inReVerb)
  76. {
  77. #ifdef ZT_ENABLE_CLUSTER
  78. bool suboptimalPath = false;
  79. if ((RR->cluster)&&(hops == 0)) {
  80. // Note: findBetterEndpoint() is first since we still want to check
  81. // for a better endpoint even if we don't actually send a redirect.
  82. InetAddress redirectTo;
  83. 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) ) {
  84. if (_vProto >= 5) {
  85. // For newer peers we can send a more idiomatic verb: PUSH_DIRECT_PATHS.
  86. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_PUSH_DIRECT_PATHS);
  87. outp.append((uint16_t)1); // count == 1
  88. outp.append((uint8_t)0); // no flags
  89. outp.append((uint16_t)0); // no extensions
  90. if (redirectTo.ss_family == AF_INET) {
  91. outp.append((uint8_t)4);
  92. outp.append((uint8_t)6);
  93. outp.append(redirectTo.rawIpData(),4);
  94. } else {
  95. outp.append((uint8_t)6);
  96. outp.append((uint8_t)18);
  97. outp.append(redirectTo.rawIpData(),16);
  98. }
  99. outp.append((uint16_t)redirectTo.port());
  100. outp.armor(_key,true);
  101. RR->antiRec->logOutgoingZT(outp.data(),outp.size());
  102. RR->node->putPacket(localAddr,remoteAddr,outp.data(),outp.size());
  103. } else {
  104. // For older peers we use RENDEZVOUS to coax them into contacting us elsewhere.
  105. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_RENDEZVOUS);
  106. outp.append((uint8_t)0); // no flags
  107. RR->identity.address().appendTo(outp);
  108. outp.append((uint16_t)redirectTo.port());
  109. if (redirectTo.ss_family == AF_INET) {
  110. outp.append((uint8_t)4);
  111. outp.append(redirectTo.rawIpData(),4);
  112. } else {
  113. outp.append((uint8_t)16);
  114. outp.append(redirectTo.rawIpData(),16);
  115. }
  116. outp.armor(_key,true);
  117. RR->antiRec->logOutgoingZT(outp.data(),outp.size());
  118. RR->node->putPacket(localAddr,remoteAddr,outp.data(),outp.size());
  119. }
  120. suboptimalPath = true;
  121. }
  122. }
  123. #endif
  124. const uint64_t now = RR->node->now();
  125. bool needMulticastGroupAnnounce = false;
  126. bool pathIsConfirmed = false;
  127. { // begin _lock
  128. Mutex::Lock _l(_lock);
  129. _lastReceive = now;
  130. if ((verb == Packet::VERB_FRAME)||(verb == Packet::VERB_EXT_FRAME))
  131. _lastUnicastFrame = now;
  132. else if (verb == Packet::VERB_MULTICAST_FRAME)
  133. _lastMulticastFrame = now;
  134. if ((now - _lastAnnouncedTo) >= ((ZT_MULTICAST_LIKE_EXPIRE / 2) - 1000)) {
  135. _lastAnnouncedTo = now;
  136. needMulticastGroupAnnounce = true;
  137. }
  138. if (hops == 0) {
  139. unsigned int np = _numPaths;
  140. for(unsigned int p=0;p<np;++p) {
  141. if ((_paths[p].address() == remoteAddr)&&(_paths[p].localAddress() == localAddr)) {
  142. _paths[p].received(now);
  143. #ifdef ZT_ENABLE_CLUSTER
  144. _paths[p].setClusterSuboptimal(suboptimalPath);
  145. #endif
  146. pathIsConfirmed = true;
  147. break;
  148. }
  149. }
  150. if (!pathIsConfirmed) {
  151. if (verb == Packet::VERB_OK) {
  152. Path *slot = (Path *)0;
  153. if (np < ZT_MAX_PEER_NETWORK_PATHS) {
  154. slot = &(_paths[np++]);
  155. } else {
  156. uint64_t slotLRmin = 0xffffffffffffffffULL;
  157. for(unsigned int p=0;p<ZT_MAX_PEER_NETWORK_PATHS;++p) {
  158. if (_paths[p].lastReceived() <= slotLRmin) {
  159. slotLRmin = _paths[p].lastReceived();
  160. slot = &(_paths[p]);
  161. }
  162. }
  163. }
  164. if (slot) {
  165. *slot = Path(localAddr,remoteAddr);
  166. slot->received(now);
  167. #ifdef ZT_ENABLE_CLUSTER
  168. slot->setClusterSuboptimal(suboptimalPath);
  169. #endif
  170. _numPaths = np;
  171. pathIsConfirmed = true;
  172. _sortPaths(now);
  173. }
  174. #ifdef ZT_ENABLE_CLUSTER
  175. if ((RR->cluster)&&(!suboptimalPath))
  176. RR->cluster->broadcastHavePeer(_id);
  177. #endif
  178. } else {
  179. /* If this path is not known, send a HELLO. We don't learn
  180. * paths without confirming that a bidirectional link is in
  181. * fact present, but any packet that decodes and authenticates
  182. * correctly is considered valid. */
  183. if ((now - _lastPathConfirmationSent) >= ZT_MIN_PATH_CONFIRMATION_INTERVAL) {
  184. _lastPathConfirmationSent = now;
  185. TRACE("got %s via unknown path %s(%s), confirming...",Packet::verbString(verb),_id.address().toString().c_str(),remoteAddr.toString().c_str());
  186. sendHELLO(RR,localAddr,remoteAddr,now);
  187. }
  188. }
  189. }
  190. }
  191. } // end _lock
  192. if (needMulticastGroupAnnounce) {
  193. const std::vector< SharedPtr<Network> > networks(RR->node->allNetworks());
  194. for(std::vector< SharedPtr<Network> >::const_iterator n(networks.begin());n!=networks.end();++n)
  195. (*n)->tryAnnounceMulticastGroupsTo(SharedPtr<Peer>(this));
  196. }
  197. }
  198. void Peer::sendHELLO(const RuntimeEnvironment *RR,const InetAddress &localAddr,const InetAddress &atAddress,uint64_t now,unsigned int ttl)
  199. {
  200. // _lock not required here since _id is immutable and nothing else is accessed
  201. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_HELLO);
  202. outp.append((unsigned char)ZT_PROTO_VERSION);
  203. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  204. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  205. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  206. outp.append(now);
  207. RR->identity.serialize(outp,false);
  208. atAddress.serialize(outp);
  209. outp.append((uint64_t)RR->topology->worldId());
  210. outp.append((uint64_t)RR->topology->worldTimestamp());
  211. outp.armor(_key,false); // HELLO is sent in the clear
  212. RR->antiRec->logOutgoingZT(outp.data(),outp.size());
  213. RR->node->putPacket(localAddr,atAddress,outp.data(),outp.size(),ttl);
  214. }
  215. bool Peer::doPingAndKeepalive(const RuntimeEnvironment *RR,uint64_t now,int inetAddressFamily)
  216. {
  217. Path *p = (Path *)0;
  218. Mutex::Lock _l(_lock);
  219. if (inetAddressFamily != 0) {
  220. p = _getBestPath(now,inetAddressFamily);
  221. } else {
  222. p = _getBestPath(now);
  223. }
  224. if (p) {
  225. if ((now - p->lastReceived()) >= ZT_PEER_DIRECT_PING_DELAY) {
  226. //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());
  227. sendHELLO(RR,p->localAddress(),p->address(),now);
  228. p->sent(now);
  229. } else if (((now - p->lastSend()) >= ZT_NAT_KEEPALIVE_DELAY)&&(!p->reliable())) {
  230. //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());
  231. _natKeepaliveBuf += (uint32_t)((now * 0x9e3779b1) >> 1); // tumble this around to send constantly varying (meaningless) payloads
  232. RR->node->putPacket(p->localAddress(),p->address(),&_natKeepaliveBuf,sizeof(_natKeepaliveBuf));
  233. p->sent(now);
  234. } else {
  235. //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());
  236. }
  237. return true;
  238. }
  239. return false;
  240. }
  241. void Peer::pushDirectPaths(const RuntimeEnvironment *RR,Path *path,uint64_t now,bool force)
  242. {
  243. #ifdef ZT_ENABLE_CLUSTER
  244. // Cluster mode disables normal PUSH_DIRECT_PATHS in favor of cluster-based peer redirection
  245. if (RR->cluster)
  246. return;
  247. #endif
  248. Mutex::Lock _l(_lock);
  249. if (((now - _lastDirectPathPushSent) >= ZT_DIRECT_PATH_PUSH_INTERVAL)||(force)) {
  250. _lastDirectPathPushSent = now;
  251. std::vector<InetAddress> dps(RR->node->directPaths());
  252. if (dps.empty())
  253. return;
  254. #ifdef ZT_TRACE
  255. {
  256. std::string ps;
  257. for(std::vector<InetAddress>::const_iterator p(dps.begin());p!=dps.end();++p) {
  258. if (ps.length() > 0)
  259. ps.push_back(',');
  260. ps.append(p->toString());
  261. }
  262. TRACE("pushing %u direct paths to %s: %s",(unsigned int)dps.size(),_id.address().toString().c_str(),ps.c_str());
  263. }
  264. #endif
  265. std::vector<InetAddress>::const_iterator p(dps.begin());
  266. while (p != dps.end()) {
  267. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_PUSH_DIRECT_PATHS);
  268. outp.addSize(2); // leave room for count
  269. unsigned int count = 0;
  270. while ((p != dps.end())&&((outp.size() + 24) < ZT_PROTO_MAX_PACKET_LENGTH)) {
  271. uint8_t addressType = 4;
  272. switch(p->ss_family) {
  273. case AF_INET:
  274. break;
  275. case AF_INET6:
  276. addressType = 6;
  277. break;
  278. default: // we currently only push IP addresses
  279. ++p;
  280. continue;
  281. }
  282. uint8_t flags = 0;
  283. /* TODO: path trust is not implemented yet
  284. switch(p->trust()) {
  285. default:
  286. break;
  287. case Path::TRUST_PRIVACY:
  288. flags |= 0x04; // no encryption
  289. break;
  290. case Path::TRUST_ULTIMATE:
  291. flags |= (0x04 | 0x08); // no encryption, no authentication (redundant but go ahead and set both)
  292. break;
  293. }
  294. */
  295. outp.append(flags);
  296. outp.append((uint16_t)0); // no extensions
  297. outp.append(addressType);
  298. outp.append((uint8_t)((addressType == 4) ? 6 : 18));
  299. outp.append(p->rawIpData(),((addressType == 4) ? 4 : 16));
  300. outp.append((uint16_t)p->port());
  301. ++count;
  302. ++p;
  303. }
  304. if (count) {
  305. outp.setAt(ZT_PACKET_IDX_PAYLOAD,(uint16_t)count);
  306. outp.armor(_key,true);
  307. path->send(RR,outp.data(),outp.size(),now);
  308. }
  309. }
  310. }
  311. }
  312. bool Peer::resetWithinScope(const RuntimeEnvironment *RR,InetAddress::IpScope scope,uint64_t now)
  313. {
  314. Mutex::Lock _l(_lock);
  315. unsigned int np = _numPaths;
  316. unsigned int x = 0;
  317. unsigned int y = 0;
  318. while (x < np) {
  319. if (_paths[x].address().ipScope() == scope) {
  320. sendHELLO(RR,_paths[x].localAddress(),_paths[x].address(),now);
  321. } else {
  322. _paths[y++] = _paths[x];
  323. }
  324. ++x;
  325. }
  326. _numPaths = y;
  327. _sortPaths(now);
  328. return (y < np);
  329. }
  330. void Peer::getBestActiveAddresses(uint64_t now,InetAddress &v4,InetAddress &v6) const
  331. {
  332. Mutex::Lock _l(_lock);
  333. uint64_t bestV4 = 0,bestV6 = 0;
  334. for(unsigned int p=0,np=_numPaths;p<np;++p) {
  335. if (_paths[p].active(now)) {
  336. uint64_t lr = _paths[p].lastReceived();
  337. if (lr) {
  338. if (_paths[p].address().isV4()) {
  339. if (lr >= bestV4) {
  340. bestV4 = lr;
  341. v4 = _paths[p].address();
  342. }
  343. } else if (_paths[p].address().isV6()) {
  344. if (lr >= bestV6) {
  345. bestV6 = lr;
  346. v6 = _paths[p].address();
  347. }
  348. }
  349. }
  350. }
  351. }
  352. }
  353. bool Peer::networkMembershipCertificatesAgree(uint64_t nwid,const CertificateOfMembership &com) const
  354. {
  355. Mutex::Lock _l(_lock);
  356. const _NetworkCom *ourCom = _networkComs.get(nwid);
  357. if (ourCom)
  358. return ourCom->com.agreesWith(com);
  359. return false;
  360. }
  361. bool Peer::validateAndSetNetworkMembershipCertificate(const RuntimeEnvironment *RR,uint64_t nwid,const CertificateOfMembership &com)
  362. {
  363. // Sanity checks
  364. if ((!com)||(com.issuedTo() != _id.address()))
  365. return false;
  366. // Return true if we already have this *exact* COM
  367. {
  368. Mutex::Lock _l(_lock);
  369. _NetworkCom *ourCom = _networkComs.get(nwid);
  370. if ((ourCom)&&(ourCom->com == com))
  371. return true;
  372. }
  373. // Check signature, log and return if cert is invalid
  374. if (com.signedBy() != Network::controllerFor(nwid)) {
  375. 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());
  376. return false; // invalid signer
  377. }
  378. if (com.signedBy() == RR->identity.address()) {
  379. // We are the controller: RR->identity.address() == controller() == cert.signedBy()
  380. // So, verify that we signed th cert ourself
  381. if (!com.verify(RR->identity)) {
  382. TRACE("rejected network membership certificate for %.16llx self signed by %s: signature check failed",(unsigned long long)_id,com.signedBy().toString().c_str());
  383. return false; // invalid signature
  384. }
  385. } else {
  386. SharedPtr<Peer> signer(RR->topology->getPeer(com.signedBy()));
  387. if (!signer) {
  388. // This would be rather odd, since this is our controller... could happen
  389. // if we get packets before we've gotten config.
  390. RR->sw->requestWhois(com.signedBy());
  391. return false; // signer unknown
  392. }
  393. if (!com.verify(signer->identity())) {
  394. TRACE("rejected network membership certificate for %.16llx signed by %s: signature check failed",(unsigned long long)_id,com.signedBy().toString().c_str());
  395. return false; // invalid signature
  396. }
  397. }
  398. // If we made it past all those checks, add or update cert in our cert info store
  399. {
  400. Mutex::Lock _l(_lock);
  401. _networkComs.set(nwid,_NetworkCom(RR->node->now(),com));
  402. }
  403. return true;
  404. }
  405. bool Peer::needsOurNetworkMembershipCertificate(uint64_t nwid,uint64_t now,bool updateLastPushedTime)
  406. {
  407. Mutex::Lock _l(_lock);
  408. uint64_t &lastPushed = _lastPushedComs[nwid];
  409. const uint64_t tmp = lastPushed;
  410. if (updateLastPushedTime)
  411. lastPushed = now;
  412. return ((now - tmp) >= (ZT_NETWORK_AUTOCONF_DELAY / 2));
  413. }
  414. void Peer::clean(const RuntimeEnvironment *RR,uint64_t now)
  415. {
  416. Mutex::Lock _l(_lock);
  417. {
  418. unsigned int np = _numPaths;
  419. unsigned int x = 0;
  420. unsigned int y = 0;
  421. while (x < np) {
  422. if (_paths[x].active(now))
  423. _paths[y++] = _paths[x];
  424. ++x;
  425. }
  426. _numPaths = y;
  427. }
  428. {
  429. uint64_t *k = (uint64_t *)0;
  430. _NetworkCom *v = (_NetworkCom *)0;
  431. Hashtable< uint64_t,_NetworkCom >::Iterator i(_networkComs);
  432. while (i.next(k,v)) {
  433. if ( (!RR->node->belongsToNetwork(*k)) && ((now - v->ts) >= ZT_PEER_NETWORK_COM_EXPIRATION) )
  434. _networkComs.erase(*k);
  435. }
  436. }
  437. {
  438. uint64_t *k = (uint64_t *)0;
  439. uint64_t *v = (uint64_t *)0;
  440. Hashtable< uint64_t,uint64_t >::Iterator i(_lastPushedComs);
  441. while (i.next(k,v)) {
  442. if ((now - *v) > (ZT_NETWORK_AUTOCONF_DELAY * 2))
  443. _lastPushedComs.erase(*k);
  444. }
  445. }
  446. }
  447. struct _SortPathsByQuality
  448. {
  449. uint64_t _now;
  450. _SortPathsByQuality(const uint64_t now) : _now(now) {}
  451. inline bool operator()(const Path &a,const Path &b) const
  452. {
  453. const uint64_t qa = (
  454. ((uint64_t)a.active(_now) << 63) |
  455. (((uint64_t)(a.preferenceRank() & 0xfff)) << 51) |
  456. ((uint64_t)a.lastReceived() & 0x7ffffffffffffULL) );
  457. const uint64_t qb = (
  458. ((uint64_t)b.active(_now) << 63) |
  459. (((uint64_t)(b.preferenceRank() & 0xfff)) << 51) |
  460. ((uint64_t)b.lastReceived() & 0x7ffffffffffffULL) );
  461. return (qb < qa); // invert sense to sort in descending order
  462. }
  463. };
  464. void Peer::_sortPaths(const uint64_t now)
  465. {
  466. // assumes _lock is locked
  467. _lastPathSort = now;
  468. std::sort(&(_paths[0]),&(_paths[_numPaths]),_SortPathsByQuality(now));
  469. }
  470. Path *Peer::_getBestPath(const uint64_t now)
  471. {
  472. // assumes _lock is locked
  473. if ((now - _lastPathSort) >= ZT_PEER_PATH_SORT_INTERVAL)
  474. _sortPaths(now);
  475. if (_paths[0].active(now)) {
  476. return &(_paths[0]);
  477. } else {
  478. _sortPaths(now);
  479. if (_paths[0].active(now))
  480. return &(_paths[0]);
  481. }
  482. return (Path *)0;
  483. }
  484. Path *Peer::_getBestPath(const uint64_t now,int inetAddressFamily)
  485. {
  486. // assumes _lock is locked
  487. if ((now - _lastPathSort) >= ZT_PEER_PATH_SORT_INTERVAL)
  488. _sortPaths(now);
  489. for(int k=0;k<2;++k) { // try once, and if it fails sort and try one more time
  490. for(unsigned int i=0;i<_numPaths;++i) {
  491. if ((_paths[i].active(now))&&((int)_paths[i].address().ss_family == inetAddressFamily))
  492. return &(_paths[i]);
  493. }
  494. _sortPaths(now);
  495. }
  496. return (Path *)0;
  497. }
  498. } // namespace ZeroTier