Peer.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2024-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include "Constants.hpp"
  14. #include "Peer.hpp"
  15. #include "Node.hpp"
  16. #include "Switch.hpp"
  17. #include "Network.hpp"
  18. #include "SelfAwareness.hpp"
  19. #include "Packet.hpp"
  20. #include "Trace.hpp"
  21. #include "InetAddress.hpp"
  22. #include <set>
  23. namespace ZeroTier {
  24. struct _PathPriorityComparisonOperator
  25. {
  26. ZT_ALWAYS_INLINE bool operator()(const SharedPtr<Path> &a,const SharedPtr<Path> &b) const
  27. {
  28. return ( ((a)&&(a->lastIn() > 0)) && ((!b)||(b->lastIn() <= 0)||(a->lastIn() < b->lastIn())) );
  29. }
  30. };
  31. Peer::Peer(const RuntimeEnvironment *renv) :
  32. RR(renv),
  33. _lastReceive(0),
  34. _lastWhoisRequestReceived(0),
  35. _lastEchoRequestReceived(0),
  36. _lastPushDirectPathsReceived(0),
  37. _lastAttemptedP2PInit(0),
  38. _lastTriedStaticPath(0),
  39. _lastPrioritizedPaths(0),
  40. _latency(0xffff),
  41. _alivePathCount(0)
  42. {
  43. }
  44. bool Peer::init(const Identity &myIdentity,const Identity &peerIdentity)
  45. {
  46. if (_id == peerIdentity)
  47. return true;
  48. _id = peerIdentity;
  49. _vProto = 0;
  50. _vMajor = 0;
  51. _vMinor = 0;
  52. _vRevision = 0;
  53. return myIdentity.agree(peerIdentity,_key);
  54. }
  55. void Peer::received(
  56. void *tPtr,
  57. const SharedPtr<Path> &path,
  58. const unsigned int hops,
  59. const uint64_t packetId,
  60. const unsigned int payloadLength,
  61. const Packet::Verb verb,
  62. const uint64_t inRePacketId,
  63. const Packet::Verb inReVerb,
  64. const uint64_t networkId)
  65. {
  66. const int64_t now = RR->node->now();
  67. _lastReceive = now;
  68. if (hops == 0) {
  69. _lock.rlock();
  70. for(int i=0;i<(int)_alivePathCount;++i) {
  71. if (_paths[i] == path) {
  72. _lock.runlock();
  73. goto path_check_done;
  74. }
  75. }
  76. _lock.runlock();
  77. if (verb == Packet::VERB_OK) {
  78. RWMutex::Lock l(_lock);
  79. int64_t lastReceiveTimeMax = 0;
  80. int lastReceiveTimeMaxAt = 0;
  81. for(int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  82. if ((_paths[i]->address().ss_family == path->address().ss_family) &&
  83. (_paths[i]->localSocket() == path->localSocket()) && // TODO: should be localInterface when multipath is integrated
  84. (_paths[i]->address().ipsEqual2(path->address()))) {
  85. // Replace older path if everything is the same except the port number.
  86. _paths[i] = path;
  87. goto path_check_done;
  88. } else {
  89. if (_paths[i]) {
  90. if (_paths[i]->lastIn() > lastReceiveTimeMax) {
  91. lastReceiveTimeMax = _paths[i]->lastIn();
  92. lastReceiveTimeMaxAt = i;
  93. }
  94. } else {
  95. lastReceiveTimeMax = 0x7fffffffffffffffLL;
  96. lastReceiveTimeMaxAt = i;
  97. }
  98. }
  99. }
  100. _lastPrioritizedPaths = now;
  101. InetAddress old;
  102. if (_paths[lastReceiveTimeMaxAt])
  103. old = _paths[lastReceiveTimeMaxAt]->address();
  104. _paths[lastReceiveTimeMaxAt] = path;
  105. _bootstrap = path->address();
  106. _prioritizePaths(now);
  107. RR->t->learnedNewPath(tPtr,packetId,_id,path->address(),old);
  108. } else {
  109. if (RR->node->shouldUsePathForZeroTierTraffic(tPtr,_id,path->localSocket(),path->address())) {
  110. RR->t->tryingNewPath(tPtr,_id,path->address(),path->address(),packetId,(uint8_t)verb,_id.address(),_id.hash(),ZT_TRACE_TRYING_NEW_PATH_REASON_PACKET_RECEIVED_FROM_UNKNOWN_PATH);
  111. sendHELLO(tPtr,path->localSocket(),path->address(),now);
  112. path->sent(now);
  113. }
  114. }
  115. }
  116. path_check_done:
  117. if ((now - _lastAttemptedP2PInit) >= ((hops == 0) ? ZT_DIRECT_PATH_PUSH_INTERVAL_HAVEPATH : ZT_DIRECT_PATH_PUSH_INTERVAL)) {
  118. _lastAttemptedP2PInit = now;
  119. InetAddress addr;
  120. if ((_bootstrap.type() == Endpoint::INETADDR_V4)||(_bootstrap.type() == Endpoint::INETADDR_V6)) {
  121. RR->t->tryingNewPath(tPtr,_id,_bootstrap.inetAddr(),InetAddress::NIL,0,0,0,nullptr,ZT_TRACE_TRYING_NEW_PATH_REASON_BOOTSTRAP_ADDRESS);
  122. sendHELLO(tPtr,-1,_bootstrap.inetAddr(),now);
  123. } if (RR->node->externalPathLookup(tPtr,_id,-1,addr)) {
  124. if (RR->node->shouldUsePathForZeroTierTraffic(tPtr,_id,-1,addr)) {
  125. RR->t->tryingNewPath(tPtr,_id,_bootstrap.inetAddr(),InetAddress::NIL,0,0,0,nullptr,ZT_TRACE_TRYING_NEW_PATH_REASON_EXPLICITLY_SUGGESTED_ADDRESS);
  126. sendHELLO(tPtr,-1,addr,now);
  127. }
  128. }
  129. std::vector<ZT_InterfaceAddress> localInterfaceAddresses(RR->node->localInterfaceAddresses());
  130. std::multimap<unsigned long,InetAddress> detectedAddresses(RR->sa->externalAddresses(now));
  131. std::set<InetAddress> addrs;
  132. for(std::vector<ZT_InterfaceAddress>::const_iterator i(localInterfaceAddresses.begin());i!=localInterfaceAddresses.end();++i)
  133. addrs.insert(asInetAddress(i->address));
  134. for(std::multimap<unsigned long,InetAddress>::const_reverse_iterator i(detectedAddresses.rbegin());i!=detectedAddresses.rend();++i) {
  135. if (i->first <= 1)
  136. break;
  137. if (addrs.count(i->second) == 0) {
  138. addrs.insert(i->second);
  139. break;
  140. }
  141. }
  142. if (!addrs.empty()) {
  143. ScopedPtr<Packet> outp(new Packet(_id.address(),RR->identity.address(),Packet::VERB_PUSH_DIRECT_PATHS));
  144. outp->addSize(2); // leave room for count
  145. unsigned int count = 0;
  146. for(std::set<InetAddress>::iterator a(addrs.begin());a!=addrs.end();++a) {
  147. uint8_t addressType = 4;
  148. uint8_t addressLength = 6;
  149. unsigned int ipLength = 4;
  150. const void *rawIpData = nullptr;
  151. uint16_t port = 0;
  152. switch(a->ss_family) {
  153. case AF_INET:
  154. rawIpData = &(reinterpret_cast<const sockaddr_in *>(&(*a))->sin_addr.s_addr);
  155. port = Utils::ntoh((uint16_t)reinterpret_cast<const sockaddr_in *>(&(*a))->sin_port);
  156. break;
  157. case AF_INET6:
  158. rawIpData = reinterpret_cast<const sockaddr_in6 *>(&(*a))->sin6_addr.s6_addr;
  159. port = Utils::ntoh((uint16_t)reinterpret_cast<const sockaddr_in6 *>(&(*a))->sin6_port);
  160. addressType = 6;
  161. addressLength = 18;
  162. ipLength = 16;
  163. break;
  164. default:
  165. continue;
  166. }
  167. outp->append((uint8_t)0); // no flags
  168. outp->append((uint16_t)0); // no extensions
  169. outp->append(addressType);
  170. outp->append(addressLength);
  171. outp->append(rawIpData,ipLength);
  172. outp->append(port);
  173. ++count;
  174. if (outp->size() >= (ZT_PROTO_MAX_PACKET_LENGTH - 32))
  175. break;
  176. }
  177. if (count > 0) {
  178. outp->setAt(ZT_PACKET_IDX_PAYLOAD,(uint16_t)count);
  179. outp->compress();
  180. outp->armor(_key,true);
  181. path->send(RR,tPtr,outp->data(),outp->size(),now);
  182. }
  183. }
  184. }
  185. }
  186. bool Peer::shouldTryPath(void *tPtr,int64_t now,const SharedPtr<Peer> &suggestedBy,const InetAddress &addr) const
  187. {
  188. int maxHaveScope = -1;
  189. {
  190. RWMutex::RLock l(_lock);
  191. for (unsigned int i = 0; i < _alivePathCount; ++i) {
  192. if (_paths[i]) {
  193. if (_paths[i]->address().ipsEqual2(addr))
  194. return false;
  195. int s = (int)_paths[i]->address().ipScope();
  196. if (s > maxHaveScope)
  197. maxHaveScope = s;
  198. }
  199. }
  200. }
  201. return ( ((int)addr.ipScope() > maxHaveScope) && RR->node->shouldUsePathForZeroTierTraffic(tPtr,_id,-1,addr) );
  202. }
  203. void Peer::sendHELLO(void *tPtr,const int64_t localSocket,const InetAddress &atAddress,int64_t now)
  204. {
  205. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_HELLO);
  206. outp.append((unsigned char)ZT_PROTO_VERSION);
  207. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  208. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  209. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  210. outp.append(now);
  211. RR->identity.serialize(outp,false);
  212. atAddress.serialize(outp);
  213. RR->node->expectReplyTo(outp.packetId());
  214. if (atAddress) {
  215. outp.armor(_key,false); // false == don't encrypt full payload, but add MAC
  216. RR->node->putPacket(tPtr,localSocket,atAddress,outp.data(),outp.size());
  217. } else {
  218. RR->sw->send(tPtr,outp,false); // false == don't encrypt full payload, but add MAC
  219. }
  220. }
  221. void Peer::ping(void *tPtr,int64_t now,const bool pingAllAddressTypes)
  222. {
  223. RWMutex::RLock l(_lock);
  224. _lastPrioritizedPaths = now;
  225. _prioritizePaths(now);
  226. if (_alivePathCount > 0) {
  227. for (unsigned int i = 0; i < _alivePathCount; ++i) {
  228. sendHELLO(tPtr,_paths[i]->localSocket(),_paths[i]->address(),now);
  229. _paths[i]->sent(now);
  230. if (!pingAllAddressTypes)
  231. return;
  232. }
  233. return;
  234. }
  235. if ((_bootstrap.type() == Endpoint::INETADDR_V4)||(_bootstrap.type() == Endpoint::INETADDR_V6))
  236. sendHELLO(tPtr,-1,_bootstrap.inetAddr(),now);
  237. SharedPtr<Peer> r(RR->topology->root());
  238. if ((r)&&(r.ptr() != this)) {
  239. SharedPtr<Path> rp(r->path(now));
  240. if (rp) {
  241. sendHELLO(tPtr,rp->localSocket(),rp->address(),now);
  242. rp->sent(now);
  243. return;
  244. }
  245. }
  246. }
  247. void Peer::resetWithinScope(void *tPtr,InetAddress::IpScope scope,int inetAddressFamily,int64_t now)
  248. {
  249. RWMutex::RLock l(_lock);
  250. for(unsigned int i=0; i < _alivePathCount; ++i) {
  251. if ((_paths[i])&&((_paths[i]->address().ss_family == inetAddressFamily)&&(_paths[i]->address().ipScope() == scope))) {
  252. sendHELLO(tPtr,_paths[i]->localSocket(),_paths[i]->address(),now);
  253. _paths[i]->sent(now);
  254. }
  255. }
  256. }
  257. void Peer::updateLatency(const unsigned int l)
  258. {
  259. if ((l > 0)&&(l < 0xffff)) {
  260. unsigned int lat = _latency;
  261. if (lat < 0xffff) {
  262. _latency = (l + l + lat) / 3;
  263. } else {
  264. _latency = l;
  265. }
  266. }
  267. }
  268. bool Peer::sendDirect(void *tPtr,const void *data,const unsigned int len,const int64_t now)
  269. {
  270. if ((now - _lastPrioritizedPaths) > ZT_PEER_PRIORITIZE_PATHS_INTERVAL) {
  271. _lastPrioritizedPaths = now;
  272. _lock.lock();
  273. _prioritizePaths(now);
  274. if (_alivePathCount == 0) {
  275. _lock.unlock();
  276. return false;
  277. }
  278. const bool r = _paths[0]->send(RR,tPtr,data,len,now);
  279. _lock.unlock();
  280. return r;
  281. } else {
  282. _lock.rlock();
  283. if (_alivePathCount == 0) {
  284. _lock.runlock();
  285. return false;
  286. }
  287. const bool r = _paths[0]->send(RR,tPtr,data,len,now);
  288. _lock.runlock();
  289. return r;
  290. }
  291. }
  292. SharedPtr<Path> Peer::path(const int64_t now)
  293. {
  294. if ((now - _lastPrioritizedPaths) > ZT_PEER_PRIORITIZE_PATHS_INTERVAL) {
  295. _lastPrioritizedPaths = now;
  296. RWMutex::Lock l(_lock);
  297. _prioritizePaths(now);
  298. if (_alivePathCount == 0)
  299. return SharedPtr<Path>();
  300. return _paths[0];
  301. } else {
  302. RWMutex::RLock l(_lock);
  303. if (_alivePathCount == 0)
  304. return SharedPtr<Path>();
  305. return _paths[0];
  306. }
  307. }
  308. void Peer::getAllPaths(std::vector< SharedPtr<Path> > &paths)
  309. {
  310. RWMutex::RLock l(_lock);
  311. paths.clear();
  312. paths.assign(_paths,_paths + _alivePathCount);
  313. }
  314. void Peer::save(void *tPtr) const
  315. {
  316. uint8_t *const buf = (uint8_t *)malloc(ZT_PEER_MARSHAL_SIZE_MAX);
  317. if (!buf) return;
  318. _lock.rlock();
  319. const int len = marshal(buf);
  320. _lock.runlock();
  321. if (len > 0) {
  322. uint64_t id[2];
  323. id[0] = _id.address().toInt();
  324. id[1] = 0;
  325. RR->node->stateObjectPut(tPtr,ZT_STATE_OBJECT_PEER,id,buf,(unsigned int)len);
  326. }
  327. free(buf);
  328. }
  329. int Peer::marshal(uint8_t data[ZT_PEER_MARSHAL_SIZE_MAX]) const
  330. {
  331. RWMutex::RLock l(_lock);
  332. data[0] = 0; // serialized peer version
  333. int s = _id.marshal(data + 1,false);
  334. if (s <= 0)
  335. return s;
  336. int p = 1 + s;
  337. s = _locator.marshal(data + p);
  338. if (s <= 0)
  339. return s;
  340. p += s;
  341. s = _bootstrap.marshal(data + p);
  342. if (s <= 0)
  343. return s;
  344. p += s;
  345. Utils::storeBigEndian(data + p,(uint16_t)_vProto);
  346. p += 2;
  347. Utils::storeBigEndian(data + p,(uint16_t)_vMajor);
  348. p += 2;
  349. Utils::storeBigEndian(data + p,(uint16_t)_vMinor);
  350. p += 2;
  351. Utils::storeBigEndian(data + p,(uint16_t)_vRevision);
  352. p += 2;
  353. data[p++] = 0;
  354. data[p++] = 0;
  355. return p;
  356. }
  357. int Peer::unmarshal(const uint8_t *restrict data,const int len)
  358. {
  359. RWMutex::Lock l(_lock);
  360. if ((len <= 1)||(data[0] != 0))
  361. return -1;
  362. int s = _id.unmarshal(data + 1,len - 1);
  363. if (s <= 0)
  364. return s;
  365. int p = 1 + s;
  366. s = _locator.unmarshal(data + p,len - p);
  367. if (s <= 0)
  368. return s;
  369. p += s;
  370. s = _bootstrap.unmarshal(data + p,len - p);
  371. if (s <= 0)
  372. return s;
  373. p += s;
  374. if ((p + 10) > len)
  375. return -1;
  376. _vProto = Utils::loadBigEndian<uint16_t>(data + p);
  377. p += 2;
  378. _vMajor = Utils::loadBigEndian<uint16_t>(data + p);
  379. p += 2;
  380. _vMinor = Utils::loadBigEndian<uint16_t>(data + p);
  381. p += 2;
  382. _vRevision = Utils::loadBigEndian<uint16_t>(data + p);
  383. p += 2;
  384. p += 2 + (int)Utils::loadBigEndian<uint16_t>(data + p);
  385. if (p > len)
  386. return -1;
  387. return p;
  388. }
  389. void Peer::_prioritizePaths(const int64_t now)
  390. {
  391. // assumes _lock is locked for writing
  392. std::sort(_paths,_paths + ZT_MAX_PEER_NETWORK_PATHS,_PathPriorityComparisonOperator());
  393. for(int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  394. if ((!_paths[i]) || (!_paths[i]->alive(now))) {
  395. _alivePathCount = i;
  396. for(;i<ZT_MAX_PEER_NETWORK_PATHS;++i)
  397. _paths[i].zero();
  398. return;
  399. }
  400. }
  401. }
  402. } // namespace ZeroTier