Peer.cpp 16 KB

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