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