Peer.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. _vMajor(0),
  45. _vMinor(0),
  46. _vRevision(0),
  47. _id(peerIdentity),
  48. _numPaths(0),
  49. _latency(0)
  50. {
  51. if (!myIdentity.agree(peerIdentity,_key,ZT_PEER_SECRET_KEY_LENGTH))
  52. throw std::runtime_error("new peer identity key agreement failed");
  53. }
  54. void Peer::received(
  55. const RuntimeEnvironment *RR,
  56. const InetAddress &remoteAddr,
  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);
  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);
  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. if ((now - _lastPathConfirmationSent) >= ZT_MIN_PATH_CONFIRMATION_INTERVAL) {
  106. _lastPathConfirmationSent = now;
  107. TRACE("got %s via unknown path %s(%s), confirming...",Packet::verbString(verb),_id.address().toString().c_str(),remoteAddr.toString().c_str());
  108. attemptToContactAt(RR,remoteAddr,now);
  109. }
  110. }
  111. }
  112. }
  113. /* Announce multicast groups of interest to direct peers if they are
  114. * considered authorized members of a given network. Also announce to
  115. * supernodes and network controllers. */
  116. if ((pathIsConfirmed)&&((now - _lastAnnouncedTo) >= ((ZT_MULTICAST_LIKE_EXPIRE / 2) - 1000))) {
  117. _lastAnnouncedTo = now;
  118. const bool isSupernode = RR->topology->isSupernode(_id.address());
  119. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  120. const std::vector< SharedPtr<Network> > networks(RR->node->allNetworks());
  121. for(std::vector< SharedPtr<Network> >::const_iterator n(networks.begin());n!=networks.end();++n) {
  122. if ( (isSupernode) || ((*n)->isAllowed(_id.address())) ) {
  123. const std::vector<MulticastGroup> mgs((*n)->allMulticastGroups());
  124. for(std::vector<MulticastGroup>::const_iterator mg(mgs.begin());mg!=mgs.end();++mg) {
  125. if ((outp.size() + 18) > ZT_UDP_DEFAULT_PAYLOAD_MTU) {
  126. outp.armor(_key,true);
  127. RR->node->putPacket(remoteAddr,outp.data(),outp.size());
  128. outp.reset(_id.address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  129. }
  130. // network ID, MAC, ADI
  131. outp.append((uint64_t)(*n)->id());
  132. mg->mac().appendTo(outp);
  133. outp.append((uint32_t)mg->adi());
  134. }
  135. }
  136. }
  137. if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH) {
  138. outp.armor(_key,true);
  139. RR->node->putPacket(remoteAddr,outp.data(),outp.size());
  140. }
  141. }
  142. }
  143. if ((verb == Packet::VERB_FRAME)||(verb == Packet::VERB_EXT_FRAME))
  144. _lastUnicastFrame = now;
  145. else if (verb == Packet::VERB_MULTICAST_FRAME)
  146. _lastMulticastFrame = now;
  147. }
  148. void Peer::attemptToContactAt(const RuntimeEnvironment *RR,const InetAddress &atAddress,uint64_t now)
  149. {
  150. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_HELLO);
  151. outp.append((unsigned char)ZT_PROTO_VERSION);
  152. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  153. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  154. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  155. outp.append(now);
  156. RR->identity.serialize(outp,false);
  157. switch(atAddress.ss_family) {
  158. case AF_INET:
  159. outp.append((unsigned char)ZT_PROTO_DEST_ADDRESS_TYPE_IPV4);
  160. outp.append(atAddress.rawIpData(),4);
  161. outp.append((uint16_t)atAddress.port());
  162. break;
  163. case AF_INET6:
  164. outp.append((unsigned char)ZT_PROTO_DEST_ADDRESS_TYPE_IPV6);
  165. outp.append(atAddress.rawIpData(),16);
  166. outp.append((uint16_t)atAddress.port());
  167. break;
  168. default:
  169. outp.append((unsigned char)ZT_PROTO_DEST_ADDRESS_TYPE_NONE);
  170. break;
  171. }
  172. outp.armor(_key,false); // HELLO is sent in the clear
  173. RR->node->putPacket(atAddress,outp.data(),outp.size());
  174. }
  175. void Peer::doPingAndKeepalive(const RuntimeEnvironment *RR,uint64_t now)
  176. {
  177. Path *const bestPath = getBestPath(now);
  178. if ((bestPath)&&(bestPath->active(now))) {
  179. if ((now - bestPath->lastReceived()) >= ZT_PEER_DIRECT_PING_DELAY) {
  180. TRACE("PING %s(%s)",_id.address().toString().c_str(),bestPath->address().toString().c_str());
  181. attemptToContactAt(RR,bestPath->address(),now);
  182. bestPath->sent(now);
  183. } else if ((now - bestPath->lastSend()) >= ZT_NAT_KEEPALIVE_DELAY) {
  184. TRACE("NAT keepalive %s(%s)",_id.address().toString().c_str(),bestPath->address().toString().c_str());
  185. RR->node->putPacket(bestPath->address(),"",0);
  186. bestPath->sent(now);
  187. }
  188. }
  189. }
  190. void Peer::addPath(const Path &newp)
  191. {
  192. unsigned int np = _numPaths;
  193. for(unsigned int p=0;p<np;++p) {
  194. if (_paths[p].address() == newp.address()) {
  195. _paths[p].setFixed(newp.fixed());
  196. return;
  197. }
  198. }
  199. Path *slot = (Path *)0;
  200. if (np < ZT1_MAX_PEER_NETWORK_PATHS) {
  201. // Add new path
  202. slot = &(_paths[np++]);
  203. } else {
  204. // Replace oldest non-fixed path
  205. uint64_t slotLRmin = 0xffffffffffffffffULL;
  206. for(unsigned int p=0;p<ZT1_MAX_PEER_NETWORK_PATHS;++p) {
  207. if ((!_paths[p].fixed())&&(_paths[p].lastReceived() <= slotLRmin)) {
  208. slotLRmin = _paths[p].lastReceived();
  209. slot = &(_paths[p]);
  210. }
  211. }
  212. }
  213. if (slot) {
  214. *slot = newp;
  215. _numPaths = np;
  216. }
  217. }
  218. void Peer::clearPaths(bool fixedToo)
  219. {
  220. if (fixedToo) {
  221. _numPaths = 0;
  222. } else {
  223. unsigned int np = _numPaths;
  224. unsigned int x = 0;
  225. unsigned int y = 0;
  226. while (x < np) {
  227. if (_paths[x].fixed())
  228. _paths[y++] = _paths[x];
  229. ++x;
  230. }
  231. _numPaths = y;
  232. }
  233. }
  234. bool Peer::resetWithinScope(const RuntimeEnvironment *RR,InetAddress::IpScope scope,uint64_t now)
  235. {
  236. unsigned int np = _numPaths;
  237. unsigned int x = 0;
  238. unsigned int y = 0;
  239. while (x < np) {
  240. if (_paths[x].address().ipScope() == scope) {
  241. if (_paths[x].fixed()) {
  242. attemptToContactAt(RR,_paths[x].address(),now);
  243. _paths[y++] = _paths[x]; // keep fixed paths
  244. }
  245. } else {
  246. _paths[y++] = _paths[x]; // keep paths not in this scope
  247. }
  248. ++x;
  249. }
  250. _numPaths = y;
  251. return (y < np);
  252. }
  253. void Peer::getBestActiveAddresses(uint64_t now,InetAddress &v4,InetAddress &v6) const
  254. {
  255. uint64_t bestV4 = 0,bestV6 = 0;
  256. for(unsigned int p=0,np=_numPaths;p<np;++p) {
  257. if (_paths[p].active(now)) {
  258. uint64_t lr = _paths[p].lastReceived();
  259. if (lr) {
  260. if (_paths[p].address().isV4()) {
  261. if (lr >= bestV4) {
  262. bestV4 = lr;
  263. v4 = _paths[p].address();
  264. }
  265. } else if (_paths[p].address().isV6()) {
  266. if (lr >= bestV6) {
  267. bestV6 = lr;
  268. v6 = _paths[p].address();
  269. }
  270. }
  271. }
  272. }
  273. }
  274. }
  275. } // namespace ZeroTier