Peer.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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. namespace ZeroTier {
  37. Peer::Peer(const Identity &myIdentity,const Identity &peerIdentity)
  38. throw(std::runtime_error) :
  39. _lastUsed(0),
  40. _lastReceive(0),
  41. _lastUnicastFrame(0),
  42. _lastMulticastFrame(0),
  43. _lastAnnouncedTo(0),
  44. _lastPathConfirmationSent(0),
  45. _lastDirectPathPush(0),
  46. _vMajor(0),
  47. _vMinor(0),
  48. _vRevision(0),
  49. _id(peerIdentity),
  50. _numPaths(0),
  51. _latency(0)
  52. {
  53. if (!myIdentity.agree(peerIdentity,_key,ZT_PEER_SECRET_KEY_LENGTH))
  54. throw std::runtime_error("new peer identity key agreement failed");
  55. }
  56. void Peer::received(
  57. const RuntimeEnvironment *RR,
  58. const InetAddress &remoteAddr,
  59. unsigned int hops,
  60. uint64_t packetId,
  61. Packet::Verb verb,
  62. uint64_t inRePacketId,
  63. Packet::Verb inReVerb)
  64. {
  65. const uint64_t now = RR->node->now();
  66. _lastReceive = now;
  67. if (!hops) {
  68. bool pathIsConfirmed = false;
  69. /* Learn new paths from direct (hops == 0) packets */
  70. {
  71. unsigned int np = _numPaths;
  72. for(unsigned int p=0;p<np;++p) {
  73. if (_paths[p].address() == remoteAddr) {
  74. _paths[p].received(now);
  75. pathIsConfirmed = true;
  76. break;
  77. }
  78. }
  79. if (!pathIsConfirmed) {
  80. if ((verb == Packet::VERB_OK)&&(inReVerb == Packet::VERB_HELLO)) {
  81. // Learn paths if they've been confirmed via a HELLO
  82. RemotePath *slot = (RemotePath *)0;
  83. if (np < ZT1_MAX_PEER_NETWORK_PATHS) {
  84. // Add new path
  85. slot = &(_paths[np++]);
  86. } else {
  87. // Replace oldest non-fixed path
  88. uint64_t slotLRmin = 0xffffffffffffffffULL;
  89. for(unsigned int p=0;p<ZT1_MAX_PEER_NETWORK_PATHS;++p) {
  90. if ((!_paths[p].fixed())&&(_paths[p].lastReceived() <= slotLRmin)) {
  91. slotLRmin = _paths[p].lastReceived();
  92. slot = &(_paths[p]);
  93. }
  94. }
  95. }
  96. if (slot) {
  97. *slot = RemotePath(remoteAddr,false);
  98. slot->received(now);
  99. _numPaths = np;
  100. pathIsConfirmed = true;
  101. }
  102. } else {
  103. /* If this path is not known, send a HELLO. We don't learn
  104. * paths without confirming that a bidirectional link is in
  105. * fact present, but any packet that decodes and authenticates
  106. * correctly is considered valid. */
  107. if ((now - _lastPathConfirmationSent) >= ZT_MIN_PATH_CONFIRMATION_INTERVAL) {
  108. _lastPathConfirmationSent = now;
  109. TRACE("got %s via unknown path %s(%s), confirming...",Packet::verbString(verb),_id.address().toString().c_str(),remoteAddr.toString().c_str());
  110. attemptToContactAt(RR,remoteAddr,now);
  111. }
  112. }
  113. }
  114. }
  115. /* Announce multicast groups of interest to direct peers if they are
  116. * considered authorized members of a given network. Also announce to
  117. * root servers and network controllers. */
  118. if ((pathIsConfirmed)&&((now - _lastAnnouncedTo) >= ((ZT_MULTICAST_LIKE_EXPIRE / 2) - 1000))) {
  119. _lastAnnouncedTo = now;
  120. const bool isRoot = RR->topology->isRoot(_id);
  121. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  122. const std::vector< SharedPtr<Network> > networks(RR->node->allNetworks());
  123. for(std::vector< SharedPtr<Network> >::const_iterator n(networks.begin());n!=networks.end();++n) {
  124. if ( (isRoot) || ((*n)->isAllowed(_id.address())) ) {
  125. const std::vector<MulticastGroup> mgs((*n)->allMulticastGroups());
  126. for(std::vector<MulticastGroup>::const_iterator mg(mgs.begin());mg!=mgs.end();++mg) {
  127. if ((outp.size() + 18) > ZT_UDP_DEFAULT_PAYLOAD_MTU) {
  128. outp.armor(_key,true);
  129. RR->node->putPacket(remoteAddr,outp.data(),outp.size());
  130. outp.reset(_id.address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  131. }
  132. // network ID, MAC, ADI
  133. outp.append((uint64_t)(*n)->id());
  134. mg->mac().appendTo(outp);
  135. outp.append((uint32_t)mg->adi());
  136. }
  137. }
  138. }
  139. if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH) {
  140. outp.armor(_key,true);
  141. RR->node->putPacket(remoteAddr,outp.data(),outp.size());
  142. }
  143. }
  144. }
  145. if ((verb == Packet::VERB_FRAME)||(verb == Packet::VERB_EXT_FRAME))
  146. _lastUnicastFrame = now;
  147. else if (verb == Packet::VERB_MULTICAST_FRAME)
  148. _lastMulticastFrame = now;
  149. }
  150. RemotePath *Peer::getBestPath(uint64_t now)
  151. {
  152. RemotePath *bestPath = (RemotePath *)0;
  153. uint64_t lrMax = 0;
  154. int rank = 0;
  155. for(unsigned int p=0,np=_numPaths;p<np;++p) {
  156. if ( (_paths[p].active(now)) && ((_paths[p].lastReceived() >= lrMax)||(_paths[p].preferenceRank() >= rank)) ) {
  157. lrMax = _paths[p].lastReceived();
  158. rank = _paths[p].preferenceRank();
  159. bestPath = &(_paths[p]);
  160. }
  161. }
  162. return bestPath;
  163. }
  164. void Peer::attemptToContactAt(const RuntimeEnvironment *RR,const InetAddress &atAddress,uint64_t now)
  165. {
  166. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_HELLO);
  167. outp.append((unsigned char)ZT_PROTO_VERSION);
  168. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  169. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  170. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  171. outp.append(now);
  172. RR->identity.serialize(outp,false);
  173. switch(atAddress.ss_family) {
  174. case AF_INET:
  175. outp.append((unsigned char)ZT_PROTO_DEST_ADDRESS_TYPE_IPV4);
  176. outp.append(atAddress.rawIpData(),4);
  177. outp.append((uint16_t)atAddress.port());
  178. break;
  179. case AF_INET6:
  180. outp.append((unsigned char)ZT_PROTO_DEST_ADDRESS_TYPE_IPV6);
  181. outp.append(atAddress.rawIpData(),16);
  182. outp.append((uint16_t)atAddress.port());
  183. break;
  184. default:
  185. outp.append((unsigned char)ZT_PROTO_DEST_ADDRESS_TYPE_NONE);
  186. break;
  187. }
  188. outp.armor(_key,false); // HELLO is sent in the clear
  189. RR->node->putPacket(atAddress,outp.data(),outp.size());
  190. }
  191. void Peer::doPingAndKeepalive(const RuntimeEnvironment *RR,uint64_t now)
  192. {
  193. RemotePath *const bestPath = getBestPath(now);
  194. if ((bestPath)&&(bestPath->active(now))) {
  195. if ((now - bestPath->lastReceived()) >= ZT_PEER_DIRECT_PING_DELAY) {
  196. TRACE("PING %s(%s)",_id.address().toString().c_str(),bestPath->address().toString().c_str());
  197. attemptToContactAt(RR,bestPath->address(),now);
  198. bestPath->sent(now);
  199. } else if (((now - bestPath->lastSend()) >= ZT_NAT_KEEPALIVE_DELAY)&&(!bestPath->reliable())) {
  200. TRACE("NAT keepalive %s(%s)",_id.address().toString().c_str(),bestPath->address().toString().c_str());
  201. RR->node->putPacket(bestPath->address(),"",0);
  202. bestPath->sent(now);
  203. }
  204. }
  205. }
  206. void Peer::pushDirectPaths(const RuntimeEnvironment *RR,RemotePath *path,uint64_t now,bool force)
  207. {
  208. if ((((now - _lastDirectPathPush) >= ZT_DIRECT_PATH_PUSH_INTERVAL)||(force))) {
  209. _lastDirectPathPush = now;
  210. std::vector<Path> dps(RR->node->directPaths());
  211. /* Also push paths reported to us by non-root-server peers. This assists
  212. * with NAT traversal behind NATs that engage in strange or randomized
  213. * port assignment behavior. */
  214. std::vector<Address> rootAddresses(RR->topology->rootAddresses());
  215. std::vector< std::pair<Address,InetAddress> > surface(RR->sa->getReportedSurface());
  216. for(std::vector< std::pair<Address,InetAddress> >::const_iterator s(surface.begin());s!=surface.end();++s) {
  217. bool alreadyHave = false;
  218. for(std::vector<Path>::const_iterator p(dps.begin());p!=dps.end();++p) {
  219. if (p->address() == s->second) {
  220. alreadyHave = true;
  221. break;
  222. }
  223. }
  224. if ((!alreadyHave)&&(std::find(rootAddresses.begin(),rootAddresses.end(),s->first) == rootAddresses.end()))
  225. dps.push_back(Path(s->second,0,Path::TRUST_NORMAL));
  226. }
  227. #ifdef ZT_TRACE
  228. {
  229. std::string ps;
  230. for(std::vector<Path>::const_iterator p(dps.begin());p!=dps.end();++p) {
  231. if (ps.length() > 0)
  232. ps.push_back(',');
  233. ps.append(p->address().toString());
  234. }
  235. TRACE("pushing %u direct paths (local interface addresses) to %s: %s",(unsigned int)dps.size(),_id.address().toString().c_str(),ps.c_str());
  236. }
  237. #endif
  238. std::vector<Path>::const_iterator p(dps.begin());
  239. while (p != dps.end()) {
  240. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_PUSH_DIRECT_PATHS);
  241. outp.addSize(2); // leave room for count
  242. unsigned int count = 0;
  243. while ((p != dps.end())&&((outp.size() + 24) < ZT_PROTO_MAX_PACKET_LENGTH)) {
  244. uint8_t addressType = 4;
  245. switch(p->address().ss_family) {
  246. case AF_INET:
  247. break;
  248. case AF_INET6:
  249. addressType = 6;
  250. break;
  251. default: // we currently only push IP addresses
  252. ++p;
  253. continue;
  254. }
  255. uint8_t flags = 0;
  256. switch(p->trust()) {
  257. default:
  258. break;
  259. case Path::TRUST_PRIVACY:
  260. flags |= 0x04; // no encryption
  261. break;
  262. case Path::TRUST_ULTIMATE:
  263. flags |= (0x04 | 0x08); // no encryption, no authentication (redundant but go ahead and set both)
  264. break;
  265. }
  266. outp.append(flags);
  267. outp.append((uint16_t)0); // no extensions
  268. outp.append(addressType);
  269. outp.append((uint8_t)((addressType == 4) ? 6 : 18));
  270. outp.append(p->address().rawIpData(),((addressType == 4) ? 4 : 16));
  271. outp.append((uint16_t)p->address().port());
  272. ++count;
  273. ++p;
  274. }
  275. if (count) {
  276. outp.setAt(ZT_PACKET_IDX_PAYLOAD,(uint16_t)count);
  277. outp.armor(_key,true);
  278. path->send(RR,outp.data(),outp.size(),now);
  279. }
  280. }
  281. }
  282. }
  283. void Peer::addPath(const RemotePath &newp)
  284. {
  285. unsigned int np = _numPaths;
  286. for(unsigned int p=0;p<np;++p) {
  287. if (_paths[p].address() == newp.address()) {
  288. _paths[p].setFixed(newp.fixed());
  289. return;
  290. }
  291. }
  292. RemotePath *slot = (RemotePath *)0;
  293. if (np < ZT1_MAX_PEER_NETWORK_PATHS) {
  294. // Add new path
  295. slot = &(_paths[np++]);
  296. } else {
  297. // Replace oldest non-fixed path
  298. uint64_t slotLRmin = 0xffffffffffffffffULL;
  299. for(unsigned int p=0;p<ZT1_MAX_PEER_NETWORK_PATHS;++p) {
  300. if ((!_paths[p].fixed())&&(_paths[p].lastReceived() <= slotLRmin)) {
  301. slotLRmin = _paths[p].lastReceived();
  302. slot = &(_paths[p]);
  303. }
  304. }
  305. }
  306. if (slot) {
  307. *slot = newp;
  308. _numPaths = np;
  309. }
  310. }
  311. void Peer::clearPaths(bool fixedToo)
  312. {
  313. if (fixedToo) {
  314. _numPaths = 0;
  315. } else {
  316. unsigned int np = _numPaths;
  317. unsigned int x = 0;
  318. unsigned int y = 0;
  319. while (x < np) {
  320. if (_paths[x].fixed())
  321. _paths[y++] = _paths[x];
  322. ++x;
  323. }
  324. _numPaths = y;
  325. }
  326. }
  327. bool Peer::resetWithinScope(const RuntimeEnvironment *RR,InetAddress::IpScope scope,uint64_t now)
  328. {
  329. unsigned int np = _numPaths;
  330. unsigned int x = 0;
  331. unsigned int y = 0;
  332. while (x < np) {
  333. if (_paths[x].address().ipScope() == scope) {
  334. if (_paths[x].fixed()) {
  335. attemptToContactAt(RR,_paths[x].address(),now);
  336. _paths[y++] = _paths[x]; // keep fixed paths
  337. }
  338. } else {
  339. _paths[y++] = _paths[x]; // keep paths not in this scope
  340. }
  341. ++x;
  342. }
  343. _numPaths = y;
  344. return (y < np);
  345. }
  346. void Peer::getBestActiveAddresses(uint64_t now,InetAddress &v4,InetAddress &v6) const
  347. {
  348. uint64_t bestV4 = 0,bestV6 = 0;
  349. for(unsigned int p=0,np=_numPaths;p<np;++p) {
  350. if (_paths[p].active(now)) {
  351. uint64_t lr = _paths[p].lastReceived();
  352. if (lr) {
  353. if (_paths[p].address().isV4()) {
  354. if (lr >= bestV4) {
  355. bestV4 = lr;
  356. v4 = _paths[p].address();
  357. }
  358. } else if (_paths[p].address().isV6()) {
  359. if (lr >= bestV6) {
  360. bestV6 = lr;
  361. v6 = _paths[p].address();
  362. }
  363. }
  364. }
  365. }
  366. }
  367. }
  368. } // namespace ZeroTier