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