Peer.cpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. _vMajor(0),
  44. _vMinor(0),
  45. _vRevision(0),
  46. _id(peerIdentity),
  47. _numPaths(0),
  48. _latency(0)
  49. {
  50. if (!myIdentity.agree(peerIdentity,_key,ZT_PEER_SECRET_KEY_LENGTH))
  51. throw std::runtime_error("new peer identity key agreement failed");
  52. }
  53. void Peer::received(
  54. const RuntimeEnvironment *RR,
  55. const InetAddress &remoteAddr,
  56. int linkDesperation,
  57. unsigned int hops,
  58. uint64_t packetId,
  59. Packet::Verb verb,
  60. uint64_t inRePacketId,
  61. Packet::Verb inReVerb)
  62. {
  63. const uint64_t now = RR->node->now();
  64. _lastReceive = now;
  65. if (!hops) {
  66. bool pathIsConfirmed = false;
  67. /* Learn new paths from direct (hops == 0) packets */
  68. {
  69. unsigned int np = _numPaths;
  70. for(unsigned int p=0;p<np;++p) {
  71. if (_paths[p].address() == remoteAddr) {
  72. _paths[p].received(now,linkDesperation);
  73. pathIsConfirmed = true;
  74. break;
  75. }
  76. }
  77. if (!pathIsConfirmed) {
  78. if ((verb == Packet::VERB_OK)&&(inReVerb == Packet::VERB_HELLO)) {
  79. // Learn paths if they've been confirmed via a HELLO
  80. Path *slot = (Path *)0;
  81. if (np < ZT1_MAX_PEER_NETWORK_PATHS) {
  82. // Add new path
  83. slot = &(_paths[np++]);
  84. } else {
  85. // Replace oldest non-fixed path
  86. uint64_t slotLRmin = 0xffffffffffffffffULL;
  87. for(unsigned int p=0;p<ZT1_MAX_PEER_NETWORK_PATHS;++p) {
  88. if ((!_paths[p].fixed())&&(_paths[p].lastReceived() <= slotLRmin)) {
  89. slotLRmin = _paths[p].lastReceived();
  90. slot = &(_paths[p]);
  91. }
  92. }
  93. }
  94. if (slot) {
  95. slot->init(remoteAddr,false);
  96. slot->received(now,linkDesperation);
  97. _numPaths = np;
  98. pathIsConfirmed = true;
  99. }
  100. } else {
  101. /* If this path is not known, send a HELLO. We don't learn
  102. * paths without confirming that a bidirectional link is in
  103. * fact present, but any packet that decodes and authenticates
  104. * correctly is considered valid. */
  105. attemptToContactAt(RR,remoteAddr,linkDesperation,now);
  106. }
  107. }
  108. }
  109. /* Announce multicast groups of interest to direct peers if they are
  110. * considered authorized members of a given network. Also announce to
  111. * supernodes and network controllers. */
  112. if ((pathIsConfirmed)&&((now - _lastAnnouncedTo) >= ((ZT_MULTICAST_LIKE_EXPIRE / 2) - 1000))) {
  113. _lastAnnouncedTo = now;
  114. const bool isSupernode = RR->topology->isSupernode(_id.address());
  115. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  116. const std::vector< SharedPtr<Network> > networks(RR->node->allNetworks());
  117. for(std::vector< SharedPtr<Network> >::const_iterator n(networks.begin());n!=networks.end();++n) {
  118. if ( (isSupernode) || ((*n)->isAllowed(_id.address())) ) {
  119. const std::vector<MulticastGroup> mgs((*n)->allMulticastGroups());
  120. for(std::vector<MulticastGroup>::const_iterator mg(mgs.begin());mg!=mgs.end();++mg) {
  121. if ((outp.size() + 18) > ZT_UDP_DEFAULT_PAYLOAD_MTU) {
  122. outp.armor(_key,true);
  123. RR->node->putPacket(remoteAddr,outp.data(),outp.size(),linkDesperation);
  124. outp.reset(_id.address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  125. }
  126. // network ID, MAC, ADI
  127. outp.append((uint64_t)(*n)->id());
  128. mg->mac().appendTo(outp);
  129. outp.append((uint32_t)mg->adi());
  130. }
  131. }
  132. }
  133. if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH) {
  134. outp.armor(_key,true);
  135. RR->node->putPacket(remoteAddr,outp.data(),outp.size(),linkDesperation);
  136. }
  137. }
  138. }
  139. if ((verb == Packet::VERB_FRAME)||(verb == Packet::VERB_EXT_FRAME))
  140. _lastUnicastFrame = now;
  141. else if (verb == Packet::VERB_MULTICAST_FRAME)
  142. _lastMulticastFrame = now;
  143. }
  144. void Peer::attemptToContactAt(const RuntimeEnvironment *RR,const InetAddress &atAddress,unsigned int linkDesperation,uint64_t now)
  145. {
  146. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_HELLO);
  147. outp.append((unsigned char)ZT_PROTO_VERSION);
  148. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  149. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  150. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  151. outp.append(now);
  152. RR->identity.serialize(outp,false);
  153. switch(atAddress.ss_family) {
  154. case AF_INET:
  155. outp.append((unsigned char)ZT_PROTO_DEST_ADDRESS_TYPE_IPV4);
  156. outp.append(atAddress.rawIpData(),4);
  157. outp.append((uint16_t)atAddress.port());
  158. break;
  159. case AF_INET6:
  160. outp.append((unsigned char)ZT_PROTO_DEST_ADDRESS_TYPE_IPV6);
  161. outp.append(atAddress.rawIpData(),16);
  162. outp.append((uint16_t)atAddress.port());
  163. break;
  164. default:
  165. outp.append((unsigned char)ZT_PROTO_DEST_ADDRESS_TYPE_NONE);
  166. break;
  167. }
  168. outp.armor(_key,false); // HELLO is sent in the clear
  169. RR->node->putPacket(atAddress,outp.data(),outp.size(),linkDesperation);
  170. }
  171. void Peer::doPingAndKeepalive(const RuntimeEnvironment *RR,uint64_t now)
  172. {
  173. Path *const bestPath = getBestPath(now);
  174. if ((bestPath)&&(bestPath->active(now))) {
  175. const unsigned int desp = std::max(RR->node->coreDesperation(),bestPath->lastReceiveDesperation());
  176. if ((now - bestPath->lastReceived()) >= ZT_PEER_DIRECT_PING_DELAY) {
  177. attemptToContactAt(RR,bestPath->address(),desp,now);
  178. bestPath->sent(now);
  179. } else if ((now - bestPath->lastSend()) >= ZT_NAT_KEEPALIVE_DELAY) {
  180. // We only do keepalive if desperation is zero right now, since higher
  181. // desperation paths involve things like tunneling that do not need it.
  182. if (desp == 0) {
  183. RR->node->putPacket(bestPath->address(),"",0,0);
  184. bestPath->sent(now);
  185. }
  186. }
  187. }
  188. }
  189. void Peer::addPath(const Path &newp)
  190. {
  191. unsigned int np = _numPaths;
  192. for(unsigned int p=0;p<np;++p) {
  193. if (_paths[p].address() == newp.address()) {
  194. _paths[p].setFixed(newp.fixed());
  195. return;
  196. }
  197. }
  198. Path *slot = (Path *)0;
  199. if (np < ZT1_MAX_PEER_NETWORK_PATHS) {
  200. // Add new path
  201. slot = &(_paths[np++]);
  202. } else {
  203. // Replace oldest non-fixed path
  204. uint64_t slotLRmin = 0xffffffffffffffffULL;
  205. for(unsigned int p=0;p<ZT1_MAX_PEER_NETWORK_PATHS;++p) {
  206. if ((!_paths[p].fixed())&&(_paths[p].lastReceived() <= slotLRmin)) {
  207. slotLRmin = _paths[p].lastReceived();
  208. slot = &(_paths[p]);
  209. }
  210. }
  211. }
  212. if (slot) {
  213. *slot = newp;
  214. _numPaths = np;
  215. }
  216. }
  217. void Peer::clearPaths(bool fixedToo)
  218. {
  219. if (fixedToo) {
  220. _numPaths = 0;
  221. } else {
  222. unsigned int np = _numPaths;
  223. unsigned int x = 0;
  224. unsigned int y = 0;
  225. while (x < np) {
  226. if (_paths[x].fixed())
  227. _paths[y++] = _paths[x];
  228. ++x;
  229. }
  230. _numPaths = y;
  231. }
  232. }
  233. void Peer::resetWithinScope(const RuntimeEnvironment *RR,InetAddress::IpScope scope,uint64_t now)
  234. {
  235. unsigned int np = _numPaths;
  236. unsigned int x = 0;
  237. unsigned int y = 0;
  238. while (x < np) {
  239. if (_paths[x].address().ipScope() == scope) {
  240. if (_paths[x].fixed()) {
  241. attemptToContactAt(RR,_paths[x].address(),_paths[x].lastReceiveDesperation(),now);
  242. _paths[y++] = _paths[x]; // keep fixed paths
  243. }
  244. } else {
  245. _paths[y++] = _paths[x]; // keep paths not in this scope
  246. }
  247. ++x;
  248. }
  249. _numPaths = y;
  250. if ((y < np)&&(alive(now))) {
  251. // Try to re-establish direct connectivity to this peer if it's alive
  252. // and we have forgotten paths to it.
  253. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_NOP);
  254. RR->sw->send(outp,true);
  255. }
  256. }
  257. void Peer::getBestActiveAddresses(uint64_t now,InetAddress &v4,InetAddress &v6) const
  258. {
  259. uint64_t bestV4 = 0,bestV6 = 0;
  260. for(unsigned int p=0,np=_numPaths;p<np;++p) {
  261. if (_paths[p].active(now)) {
  262. uint64_t lr = _paths[p].lastReceived();
  263. if (lr) {
  264. if (_paths[p].address().isV4()) {
  265. if (lr >= bestV4) {
  266. bestV4 = lr;
  267. v4 = _paths[p].address();
  268. }
  269. } else if (_paths[p].address().isV6()) {
  270. if (lr >= bestV6) {
  271. bestV6 = lr;
  272. v6 = _paths[p].address();
  273. }
  274. }
  275. }
  276. }
  277. }
  278. }
  279. } // namespace ZeroTier