Peer.cpp 15 KB

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