Peer.cpp 12 KB

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