Peer.cpp 11 KB

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