Peer.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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. _lastDirectPathPushSent(0),
  50. _lastDirectPathPushReceive(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. _directPathPushCutoffCount(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 suboptimalPath = false;
  78. if ((RR->cluster)&&(hops == 0)) {
  79. // Note: findBetterEndpoint() is first since we still want to check
  80. // for a better endpoint even if we don't actually send a redirect.
  81. InetAddress redirectTo;
  82. 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) ) {
  83. if (_vProto >= 5) {
  84. // For newer peers we can send a more idiomatic verb: PUSH_DIRECT_PATHS.
  85. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_PUSH_DIRECT_PATHS);
  86. outp.append((uint16_t)1); // count == 1
  87. outp.append((uint8_t)0); // no flags
  88. outp.append((uint16_t)0); // no extensions
  89. if (redirectTo.ss_family == AF_INET) {
  90. outp.append((uint8_t)4);
  91. outp.append((uint8_t)6);
  92. outp.append(redirectTo.rawIpData(),4);
  93. } else {
  94. outp.append((uint8_t)6);
  95. outp.append((uint8_t)18);
  96. outp.append(redirectTo.rawIpData(),16);
  97. }
  98. outp.append((uint16_t)redirectTo.port());
  99. outp.armor(_key,true);
  100. RR->antiRec->logOutgoingZT(outp.data(),outp.size());
  101. RR->node->putPacket(localAddr,remoteAddr,outp.data(),outp.size());
  102. } else {
  103. // For older peers we use RENDEZVOUS to coax them into contacting us elsewhere.
  104. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_RENDEZVOUS);
  105. outp.append((uint8_t)0); // no flags
  106. RR->identity.address().appendTo(outp);
  107. outp.append((uint16_t)redirectTo.port());
  108. if (redirectTo.ss_family == AF_INET) {
  109. outp.append((uint8_t)4);
  110. outp.append(redirectTo.rawIpData(),4);
  111. } else {
  112. outp.append((uint8_t)16);
  113. outp.append(redirectTo.rawIpData(),16);
  114. }
  115. outp.armor(_key,true);
  116. RR->antiRec->logOutgoingZT(outp.data(),outp.size());
  117. RR->node->putPacket(localAddr,remoteAddr,outp.data(),outp.size());
  118. }
  119. suboptimalPath = true;
  120. }
  121. }
  122. #endif
  123. const uint64_t now = RR->node->now();
  124. bool needMulticastGroupAnnounce = 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. if ((now - _lastAnnouncedTo) >= ((ZT_MULTICAST_LIKE_EXPIRE / 2) - 1000)) {
  133. _lastAnnouncedTo = now;
  134. needMulticastGroupAnnounce = true;
  135. }
  136. if (hops == 0) {
  137. bool pathIsConfirmed = false;
  138. unsigned int np = _numPaths;
  139. for(unsigned int p=0;p<np;++p) {
  140. if ((_paths[p].address() == remoteAddr)&&(_paths[p].localAddress() == localAddr)) {
  141. _paths[p].received(now);
  142. #ifdef ZT_ENABLE_CLUSTER
  143. _paths[p].setClusterSuboptimal(suboptimalPath);
  144. #endif
  145. pathIsConfirmed = true;
  146. break;
  147. }
  148. }
  149. if (!pathIsConfirmed) {
  150. if (verb == Packet::VERB_OK) {
  151. Path *slot = (Path *)0;
  152. if (np < ZT_MAX_PEER_NETWORK_PATHS) {
  153. slot = &(_paths[np++]);
  154. } else {
  155. uint64_t slotLRmin = 0xffffffffffffffffULL;
  156. for(unsigned int p=0;p<ZT_MAX_PEER_NETWORK_PATHS;++p) {
  157. if (_paths[p].lastReceived() <= slotLRmin) {
  158. slotLRmin = _paths[p].lastReceived();
  159. slot = &(_paths[p]);
  160. }
  161. }
  162. }
  163. if (slot) {
  164. *slot = Path(localAddr,remoteAddr);
  165. slot->received(now);
  166. #ifdef ZT_ENABLE_CLUSTER
  167. slot->setClusterSuboptimal(suboptimalPath);
  168. #endif
  169. _numPaths = np;
  170. }
  171. #ifdef ZT_ENABLE_CLUSTER
  172. if (RR->cluster)
  173. RR->cluster->broadcastHavePeer(_id);
  174. #endif
  175. } else {
  176. TRACE("got %s via unknown path %s(%s), confirming...",Packet::verbString(verb),_id.address().toString().c_str(),remoteAddr.toString().c_str());
  177. if ( (_vProto >= 5) && ( !((_vMajor == 1)&&(_vMinor == 1)&&(_vRevision == 0)) ) ) {
  178. // 1.1.1 and newer nodes support ECHO, which is smaller -- but 1.1.0 has a bug so use HELLO there too
  179. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_ECHO);
  180. outp.armor(_key,true);
  181. RR->node->putPacket(localAddr,remoteAddr,outp.data(),outp.size());
  182. } else {
  183. sendHELLO(RR,localAddr,remoteAddr,now);
  184. }
  185. }
  186. }
  187. }
  188. } // end _lock
  189. if (needMulticastGroupAnnounce) {
  190. const std::vector< SharedPtr<Network> > networks(RR->node->allNetworks());
  191. for(std::vector< SharedPtr<Network> >::const_iterator n(networks.begin());n!=networks.end();++n)
  192. (*n)->tryAnnounceMulticastGroupsTo(SharedPtr<Peer>(this));
  193. }
  194. }
  195. void Peer::sendHELLO(const RuntimeEnvironment *RR,const InetAddress &localAddr,const InetAddress &atAddress,uint64_t now,unsigned int ttl)
  196. {
  197. // _lock not required here since _id is immutable and nothing else is accessed
  198. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_HELLO);
  199. outp.append((unsigned char)ZT_PROTO_VERSION);
  200. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  201. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  202. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  203. outp.append(now);
  204. RR->identity.serialize(outp,false);
  205. atAddress.serialize(outp);
  206. outp.append((uint64_t)RR->topology->worldId());
  207. outp.append((uint64_t)RR->topology->worldTimestamp());
  208. outp.armor(_key,false); // HELLO is sent in the clear
  209. RR->antiRec->logOutgoingZT(outp.data(),outp.size());
  210. RR->node->putPacket(localAddr,atAddress,outp.data(),outp.size(),ttl);
  211. }
  212. bool Peer::doPingAndKeepalive(const RuntimeEnvironment *RR,uint64_t now,int inetAddressFamily)
  213. {
  214. Path *p = (Path *)0;
  215. Mutex::Lock _l(_lock);
  216. if (inetAddressFamily != 0) {
  217. p = _getBestPath(now,inetAddressFamily);
  218. } else {
  219. p = _getBestPath(now);
  220. }
  221. if (p) {
  222. if ((now - p->lastReceived()) >= ZT_PEER_DIRECT_PING_DELAY) {
  223. //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());
  224. sendHELLO(RR,p->localAddress(),p->address(),now);
  225. p->sent(now);
  226. } else if (((now - p->lastSend()) >= ZT_NAT_KEEPALIVE_DELAY)&&(!p->reliable())) {
  227. //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());
  228. _natKeepaliveBuf += (uint32_t)((now * 0x9e3779b1) >> 1); // tumble this around to send constantly varying (meaningless) payloads
  229. RR->node->putPacket(p->localAddress(),p->address(),&_natKeepaliveBuf,sizeof(_natKeepaliveBuf));
  230. p->sent(now);
  231. } else {
  232. //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());
  233. }
  234. return true;
  235. }
  236. return false;
  237. }
  238. void Peer::pushDirectPaths(const RuntimeEnvironment *RR,Path *path,uint64_t now,bool force)
  239. {
  240. #ifdef ZT_ENABLE_CLUSTER
  241. // Cluster mode disables normal PUSH_DIRECT_PATHS in favor of cluster-based peer redirection
  242. if (RR->cluster)
  243. return;
  244. #endif
  245. Mutex::Lock _l(_lock);
  246. if (((now - _lastDirectPathPushSent) >= ZT_DIRECT_PATH_PUSH_INTERVAL)||(force)) {
  247. _lastDirectPathPushSent = now;
  248. std::vector<InetAddress> dps(RR->node->directPaths());
  249. if (dps.empty())
  250. return;
  251. #ifdef ZT_TRACE
  252. {
  253. std::string ps;
  254. for(std::vector<InetAddress>::const_iterator p(dps.begin());p!=dps.end();++p) {
  255. if (ps.length() > 0)
  256. ps.push_back(',');
  257. ps.append(p->toString());
  258. }
  259. TRACE("pushing %u direct paths to %s: %s",(unsigned int)dps.size(),_id.address().toString().c_str(),ps.c_str());
  260. }
  261. #endif
  262. std::vector<InetAddress>::const_iterator p(dps.begin());
  263. while (p != dps.end()) {
  264. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_PUSH_DIRECT_PATHS);
  265. outp.addSize(2); // leave room for count
  266. unsigned int count = 0;
  267. while ((p != dps.end())&&((outp.size() + 24) < ZT_PROTO_MAX_PACKET_LENGTH)) {
  268. uint8_t addressType = 4;
  269. switch(p->ss_family) {
  270. case AF_INET:
  271. break;
  272. case AF_INET6:
  273. addressType = 6;
  274. break;
  275. default: // we currently only push IP addresses
  276. ++p;
  277. continue;
  278. }
  279. outp.append((uint8_t)0); // no flags
  280. outp.append((uint16_t)0); // no extensions
  281. outp.append(addressType);
  282. outp.append((uint8_t)((addressType == 4) ? 6 : 18));
  283. outp.append(p->rawIpData(),((addressType == 4) ? 4 : 16));
  284. outp.append((uint16_t)p->port());
  285. ++count;
  286. ++p;
  287. }
  288. if (count) {
  289. outp.setAt(ZT_PACKET_IDX_PAYLOAD,(uint16_t)count);
  290. outp.armor(_key,true);
  291. path->send(RR,outp.data(),outp.size(),now);
  292. }
  293. }
  294. }
  295. }
  296. bool Peer::resetWithinScope(const RuntimeEnvironment *RR,InetAddress::IpScope scope,uint64_t now)
  297. {
  298. Mutex::Lock _l(_lock);
  299. unsigned int np = _numPaths;
  300. unsigned int x = 0;
  301. unsigned int y = 0;
  302. while (x < np) {
  303. if (_paths[x].address().ipScope() == scope) {
  304. sendHELLO(RR,_paths[x].localAddress(),_paths[x].address(),now);
  305. } else {
  306. _paths[y++] = _paths[x];
  307. }
  308. ++x;
  309. }
  310. _numPaths = y;
  311. return (y < np);
  312. }
  313. void Peer::getBestActiveAddresses(uint64_t now,InetAddress &v4,InetAddress &v6) const
  314. {
  315. Mutex::Lock _l(_lock);
  316. uint64_t bestV4 = 0,bestV6 = 0;
  317. for(unsigned int p=0,np=_numPaths;p<np;++p) {
  318. if (_paths[p].active(now)) {
  319. uint64_t lr = _paths[p].lastReceived();
  320. if (lr) {
  321. if (_paths[p].address().isV4()) {
  322. if (lr >= bestV4) {
  323. bestV4 = lr;
  324. v4 = _paths[p].address();
  325. }
  326. } else if (_paths[p].address().isV6()) {
  327. if (lr >= bestV6) {
  328. bestV6 = lr;
  329. v6 = _paths[p].address();
  330. }
  331. }
  332. }
  333. }
  334. }
  335. }
  336. bool Peer::networkMembershipCertificatesAgree(uint64_t nwid,const CertificateOfMembership &com) const
  337. {
  338. Mutex::Lock _l(_lock);
  339. const _NetworkCom *ourCom = _networkComs.get(nwid);
  340. if (ourCom)
  341. return ourCom->com.agreesWith(com);
  342. return false;
  343. }
  344. bool Peer::validateAndSetNetworkMembershipCertificate(const RuntimeEnvironment *RR,uint64_t nwid,const CertificateOfMembership &com)
  345. {
  346. // Sanity checks
  347. if ((!com)||(com.issuedTo() != _id.address()))
  348. return false;
  349. // Return true if we already have this *exact* COM
  350. {
  351. Mutex::Lock _l(_lock);
  352. _NetworkCom *ourCom = _networkComs.get(nwid);
  353. if ((ourCom)&&(ourCom->com == com))
  354. return true;
  355. }
  356. // Check signature, log and return if cert is invalid
  357. if (com.signedBy() != Network::controllerFor(nwid)) {
  358. 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());
  359. return false; // invalid signer
  360. }
  361. if (com.signedBy() == RR->identity.address()) {
  362. // We are the controller: RR->identity.address() == controller() == cert.signedBy()
  363. // So, verify that we signed th cert ourself
  364. if (!com.verify(RR->identity)) {
  365. TRACE("rejected network membership certificate for %.16llx self signed by %s: signature check failed",(unsigned long long)_id,com.signedBy().toString().c_str());
  366. return false; // invalid signature
  367. }
  368. } else {
  369. SharedPtr<Peer> signer(RR->topology->getPeer(com.signedBy()));
  370. if (!signer) {
  371. // This would be rather odd, since this is our controller... could happen
  372. // if we get packets before we've gotten config.
  373. RR->sw->requestWhois(com.signedBy());
  374. return false; // signer unknown
  375. }
  376. if (!com.verify(signer->identity())) {
  377. TRACE("rejected network membership certificate for %.16llx signed by %s: signature check failed",(unsigned long long)_id,com.signedBy().toString().c_str());
  378. return false; // invalid signature
  379. }
  380. }
  381. // If we made it past all those checks, add or update cert in our cert info store
  382. {
  383. Mutex::Lock _l(_lock);
  384. _networkComs.set(nwid,_NetworkCom(RR->node->now(),com));
  385. }
  386. return true;
  387. }
  388. bool Peer::needsOurNetworkMembershipCertificate(uint64_t nwid,uint64_t now,bool updateLastPushedTime)
  389. {
  390. Mutex::Lock _l(_lock);
  391. uint64_t &lastPushed = _lastPushedComs[nwid];
  392. const uint64_t tmp = lastPushed;
  393. if (updateLastPushedTime)
  394. lastPushed = now;
  395. return ((now - tmp) >= (ZT_NETWORK_AUTOCONF_DELAY / 2));
  396. }
  397. void Peer::clean(const RuntimeEnvironment *RR,uint64_t now)
  398. {
  399. Mutex::Lock _l(_lock);
  400. {
  401. unsigned int np = _numPaths;
  402. unsigned int x = 0;
  403. unsigned int y = 0;
  404. while (x < np) {
  405. if (_paths[x].active(now))
  406. _paths[y++] = _paths[x];
  407. ++x;
  408. }
  409. _numPaths = y;
  410. }
  411. {
  412. uint64_t *k = (uint64_t *)0;
  413. _NetworkCom *v = (_NetworkCom *)0;
  414. Hashtable< uint64_t,_NetworkCom >::Iterator i(_networkComs);
  415. while (i.next(k,v)) {
  416. if ( (!RR->node->belongsToNetwork(*k)) && ((now - v->ts) >= ZT_PEER_NETWORK_COM_EXPIRATION) )
  417. _networkComs.erase(*k);
  418. }
  419. }
  420. {
  421. uint64_t *k = (uint64_t *)0;
  422. uint64_t *v = (uint64_t *)0;
  423. Hashtable< uint64_t,uint64_t >::Iterator i(_lastPushedComs);
  424. while (i.next(k,v)) {
  425. if ((now - *v) > (ZT_NETWORK_AUTOCONF_DELAY * 2))
  426. _lastPushedComs.erase(*k);
  427. }
  428. }
  429. }
  430. Path *Peer::_getBestPath(const uint64_t now)
  431. {
  432. // assumes _lock is locked
  433. Path *bestPath = (Path *)0;
  434. uint64_t bestPathScore = 0;
  435. for(unsigned int i=0;i<_numPaths;++i) {
  436. const uint64_t score = _paths[i].score();
  437. if ((score >= bestPathScore)&&(_paths[i].active(now))) {
  438. bestPathScore = score;
  439. bestPath = &(_paths[i]);
  440. }
  441. }
  442. return bestPath;
  443. }
  444. Path *Peer::_getBestPath(const uint64_t now,int inetAddressFamily)
  445. {
  446. // assumes _lock is locked
  447. Path *bestPath = (Path *)0;
  448. uint64_t bestPathScore = 0;
  449. for(unsigned int i=0;i<_numPaths;++i) {
  450. const uint64_t score = _paths[i].score();
  451. if (((int)_paths[i].address().ss_family == inetAddressFamily)&&(score >= bestPathScore)&&(_paths[i].active(now))) {
  452. bestPathScore = score;
  453. bestPath = &(_paths[i]);
  454. }
  455. }
  456. return bestPath;
  457. }
  458. } // namespace ZeroTier