Peer.cpp 14 KB

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