Switch.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/
  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. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <algorithm>
  21. #include <utility>
  22. #include <stdexcept>
  23. #include "../version.h"
  24. #include "../include/ZeroTierOne.h"
  25. #include "Constants.hpp"
  26. #include "RuntimeEnvironment.hpp"
  27. #include "Switch.hpp"
  28. #include "Node.hpp"
  29. #include "InetAddress.hpp"
  30. #include "Topology.hpp"
  31. #include "Peer.hpp"
  32. #include "SelfAwareness.hpp"
  33. #include "Packet.hpp"
  34. #include "Cluster.hpp"
  35. namespace ZeroTier {
  36. #ifdef ZT_TRACE
  37. static const char *etherTypeName(const unsigned int etherType)
  38. {
  39. switch(etherType) {
  40. case ZT_ETHERTYPE_IPV4: return "IPV4";
  41. case ZT_ETHERTYPE_ARP: return "ARP";
  42. case ZT_ETHERTYPE_RARP: return "RARP";
  43. case ZT_ETHERTYPE_ATALK: return "ATALK";
  44. case ZT_ETHERTYPE_AARP: return "AARP";
  45. case ZT_ETHERTYPE_IPX_A: return "IPX_A";
  46. case ZT_ETHERTYPE_IPX_B: return "IPX_B";
  47. case ZT_ETHERTYPE_IPV6: return "IPV6";
  48. }
  49. return "UNKNOWN";
  50. }
  51. #endif // ZT_TRACE
  52. Switch::Switch(const RuntimeEnvironment *renv) :
  53. RR(renv),
  54. _lastBeaconResponse(0),
  55. _outstandingWhoisRequests(32),
  56. _lastUniteAttempt(8) // only really used on root servers and upstreams, and it'll grow there just fine
  57. {
  58. }
  59. Switch::~Switch()
  60. {
  61. }
  62. void Switch::onRemotePacket(const InetAddress &localAddr,const InetAddress &fromAddr,const void *data,unsigned int len)
  63. {
  64. try {
  65. const uint64_t now = RR->node->now();
  66. if (len == 13) {
  67. /* LEGACY: before VERB_PUSH_DIRECT_PATHS, peers used broadcast
  68. * announcements on the LAN to solve the 'same network problem.' We
  69. * no longer send these, but we'll listen for them for a while to
  70. * locate peers with versions <1.0.4. */
  71. Address beaconAddr(reinterpret_cast<const char *>(data) + 8,5);
  72. if (beaconAddr == RR->identity.address())
  73. return;
  74. if (!RR->node->shouldUsePathForZeroTierTraffic(localAddr,fromAddr))
  75. return;
  76. SharedPtr<Peer> peer(RR->topology->getPeer(beaconAddr));
  77. if (peer) { // we'll only respond to beacons from known peers
  78. if ((now - _lastBeaconResponse) >= 2500) { // limit rate of responses
  79. _lastBeaconResponse = now;
  80. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_NOP);
  81. outp.armor(peer->key(),true);
  82. RR->node->putPacket(localAddr,fromAddr,outp.data(),outp.size());
  83. }
  84. }
  85. } else if (len > ZT_PROTO_MIN_FRAGMENT_LENGTH) { // min length check is important!
  86. if (reinterpret_cast<const uint8_t *>(data)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] == ZT_PACKET_FRAGMENT_INDICATOR) {
  87. // Handle fragment ----------------------------------------------------
  88. Packet::Fragment fragment(data,len);
  89. const Address destination(fragment.destination());
  90. if (destination != RR->identity.address()) {
  91. // Fragment is not for us, so try to relay it
  92. if (fragment.hops() < ZT_RELAY_MAX_HOPS) {
  93. fragment.incrementHops();
  94. // Note: we don't bother initiating NAT-t for fragments, since heads will set that off.
  95. // It wouldn't hurt anything, just redundant and unnecessary.
  96. SharedPtr<Peer> relayTo = RR->topology->getPeer(destination);
  97. if ((!relayTo)||(!relayTo->send(fragment.data(),fragment.size(),now))) {
  98. #ifdef ZT_ENABLE_CLUSTER
  99. if (RR->cluster) {
  100. RR->cluster->sendViaCluster(Address(),destination,fragment.data(),fragment.size(),false);
  101. return;
  102. }
  103. #endif
  104. // Don't know peer or no direct path -- so relay via root server
  105. relayTo = RR->topology->getBestRoot();
  106. if (relayTo)
  107. relayTo->send(fragment.data(),fragment.size(),now);
  108. }
  109. } else {
  110. TRACE("dropped relay [fragment](%s) -> %s, max hops exceeded",fromAddr.toString().c_str(),destination.toString().c_str());
  111. }
  112. } else {
  113. // Fragment looks like ours
  114. const uint64_t fragmentPacketId = fragment.packetId();
  115. const unsigned int fragmentNumber = fragment.fragmentNumber();
  116. const unsigned int totalFragments = fragment.totalFragments();
  117. if ((totalFragments <= ZT_MAX_PACKET_FRAGMENTS)&&(fragmentNumber < ZT_MAX_PACKET_FRAGMENTS)&&(fragmentNumber > 0)&&(totalFragments > 1)) {
  118. // Fragment appears basically sane. Its fragment number must be
  119. // 1 or more, since a Packet with fragmented bit set is fragment 0.
  120. // Total fragments must be more than 1, otherwise why are we
  121. // seeing a Packet::Fragment?
  122. Mutex::Lock _l(_rxQueue_m);
  123. RXQueueEntry *const rq = _findRXQueueEntry(now,fragmentPacketId);
  124. if ((!rq->timestamp)||(rq->packetId != fragmentPacketId)) {
  125. // No packet found, so we received a fragment without its head.
  126. //TRACE("fragment (%u/%u) of %.16llx from %s",fragmentNumber + 1,totalFragments,fragmentPacketId,fromAddr.toString().c_str());
  127. rq->timestamp = now;
  128. rq->packetId = fragmentPacketId;
  129. rq->frags[fragmentNumber - 1] = fragment;
  130. rq->totalFragments = totalFragments; // total fragment count is known
  131. rq->haveFragments = 1 << fragmentNumber; // we have only this fragment
  132. rq->complete = false;
  133. } else if (!(rq->haveFragments & (1 << fragmentNumber))) {
  134. // We have other fragments and maybe the head, so add this one and check
  135. //TRACE("fragment (%u/%u) of %.16llx from %s",fragmentNumber + 1,totalFragments,fragmentPacketId,fromAddr.toString().c_str());
  136. rq->frags[fragmentNumber - 1] = fragment;
  137. rq->totalFragments = totalFragments;
  138. if (Utils::countBits(rq->haveFragments |= (1 << fragmentNumber)) == totalFragments) {
  139. // We have all fragments -- assemble and process full Packet
  140. //TRACE("packet %.16llx is complete, assembling and processing...",fragmentPacketId);
  141. for(unsigned int f=1;f<totalFragments;++f)
  142. rq->frag0.append(rq->frags[f - 1].payload(),rq->frags[f - 1].payloadLength());
  143. if (rq->frag0.tryDecode(RR,false)) {
  144. rq->timestamp = 0; // packet decoded, free entry
  145. } else {
  146. rq->complete = true; // set complete flag but leave entry since it probably needs WHOIS or something
  147. }
  148. }
  149. } // else this is a duplicate fragment, ignore
  150. }
  151. }
  152. // --------------------------------------------------------------------
  153. } else if (len >= ZT_PROTO_MIN_PACKET_LENGTH) { // min length check is important!
  154. // Handle packet head -------------------------------------------------
  155. // See packet format in Packet.hpp to understand this
  156. const uint64_t packetId = (
  157. (((uint64_t)reinterpret_cast<const uint8_t *>(data)[0]) << 56) |
  158. (((uint64_t)reinterpret_cast<const uint8_t *>(data)[1]) << 48) |
  159. (((uint64_t)reinterpret_cast<const uint8_t *>(data)[2]) << 40) |
  160. (((uint64_t)reinterpret_cast<const uint8_t *>(data)[3]) << 32) |
  161. (((uint64_t)reinterpret_cast<const uint8_t *>(data)[4]) << 24) |
  162. (((uint64_t)reinterpret_cast<const uint8_t *>(data)[5]) << 16) |
  163. (((uint64_t)reinterpret_cast<const uint8_t *>(data)[6]) << 8) |
  164. ((uint64_t)reinterpret_cast<const uint8_t *>(data)[7])
  165. );
  166. const Address destination(reinterpret_cast<const uint8_t *>(data) + 8,ZT_ADDRESS_LENGTH);
  167. const Address source(reinterpret_cast<const uint8_t *>(data) + 13,ZT_ADDRESS_LENGTH);
  168. // Catch this and toss it -- it would never work, but it could happen if we somehow
  169. // mistakenly guessed an address we're bound to as a destination for another peer.
  170. if (source == RR->identity.address())
  171. return;
  172. //TRACE("<< %.16llx %s -> %s (size: %u)",(unsigned long long)packet->packetId(),source.toString().c_str(),destination.toString().c_str(),packet->size());
  173. if (destination != RR->identity.address()) {
  174. Packet packet(data,len);
  175. // Packet is not for us, so try to relay it
  176. if (packet.hops() < ZT_RELAY_MAX_HOPS) {
  177. packet.incrementHops();
  178. SharedPtr<Peer> relayTo = RR->topology->getPeer(destination);
  179. if ((relayTo)&&((relayTo->send(packet.data(),packet.size(),now)))) {
  180. Mutex::Lock _l(_lastUniteAttempt_m);
  181. uint64_t &luts = _lastUniteAttempt[_LastUniteKey(source,destination)];
  182. if ((now - luts) >= ZT_MIN_UNITE_INTERVAL) {
  183. luts = now;
  184. unite(source,destination);
  185. }
  186. } else {
  187. #ifdef ZT_ENABLE_CLUSTER
  188. if (RR->cluster) {
  189. bool shouldUnite;
  190. {
  191. Mutex::Lock _l(_lastUniteAttempt_m);
  192. uint64_t &luts = _lastUniteAttempt[_LastUniteKey(source,destination)];
  193. shouldUnite = ((now - luts) >= ZT_MIN_UNITE_INTERVAL);
  194. if (shouldUnite)
  195. luts = now;
  196. }
  197. RR->cluster->sendViaCluster(source,destination,packet.data(),packet.size(),shouldUnite);
  198. return;
  199. }
  200. #endif
  201. relayTo = RR->topology->getBestRoot(&source,1,true);
  202. if (relayTo)
  203. relayTo->send(packet.data(),packet.size(),now);
  204. }
  205. } else {
  206. TRACE("dropped relay %s(%s) -> %s, max hops exceeded",packet.source().toString().c_str(),fromAddr.toString().c_str(),destination.toString().c_str());
  207. }
  208. } else if ((reinterpret_cast<const uint8_t *>(data)[ZT_PACKET_IDX_FLAGS] & ZT_PROTO_FLAG_FRAGMENTED) != 0) {
  209. // Packet is the head of a fragmented packet series
  210. Mutex::Lock _l(_rxQueue_m);
  211. RXQueueEntry *const rq = _findRXQueueEntry(now,packetId);
  212. if ((!rq->timestamp)||(rq->packetId != packetId)) {
  213. // If we have no other fragments yet, create an entry and save the head
  214. //TRACE("fragment (0/?) of %.16llx from %s",pid,fromAddr.toString().c_str());
  215. rq->timestamp = now;
  216. rq->packetId = packetId;
  217. rq->frag0.init(data,len,localAddr,fromAddr,now);
  218. rq->totalFragments = 0;
  219. rq->haveFragments = 1;
  220. rq->complete = false;
  221. } else if (!(rq->haveFragments & 1)) {
  222. // If we have other fragments but no head, see if we are complete with the head
  223. if ((rq->totalFragments > 1)&&(Utils::countBits(rq->haveFragments |= 1) == rq->totalFragments)) {
  224. // We have all fragments -- assemble and process full Packet
  225. //TRACE("packet %.16llx is complete, assembling and processing...",pid);
  226. rq->frag0.init(data,len,localAddr,fromAddr,now);
  227. for(unsigned int f=1;f<rq->totalFragments;++f)
  228. rq->frag0.append(rq->frags[f - 1].payload(),rq->frags[f - 1].payloadLength());
  229. if (rq->frag0.tryDecode(RR,false)) {
  230. rq->timestamp = 0; // packet decoded, free entry
  231. } else {
  232. rq->complete = true; // set complete flag but leave entry since it probably needs WHOIS or something
  233. }
  234. } else {
  235. // Still waiting on more fragments, but keep the head
  236. rq->frag0.init(data,len,localAddr,fromAddr,now);
  237. }
  238. } // else this is a duplicate head, ignore
  239. } else {
  240. // Packet is unfragmented, so just process it
  241. IncomingPacket packet(data,len,localAddr,fromAddr,now);
  242. if (!packet.tryDecode(RR,false)) {
  243. Mutex::Lock _l(_rxQueue_m);
  244. RXQueueEntry *rq = &(_rxQueue[ZT_RX_QUEUE_SIZE - 1]);
  245. unsigned long i = ZT_RX_QUEUE_SIZE - 1;
  246. while ((i)&&(rq->timestamp)) {
  247. RXQueueEntry *tmp = &(_rxQueue[--i]);
  248. if (tmp->timestamp < rq->timestamp)
  249. rq = tmp;
  250. }
  251. rq->timestamp = now;
  252. rq->packetId = packetId;
  253. rq->frag0 = packet;
  254. rq->totalFragments = 1;
  255. rq->haveFragments = 1;
  256. rq->complete = true;
  257. }
  258. }
  259. // --------------------------------------------------------------------
  260. }
  261. }
  262. } catch (std::exception &ex) {
  263. TRACE("dropped packet from %s: unexpected exception: %s",fromAddr.toString().c_str(),ex.what());
  264. } catch ( ... ) {
  265. TRACE("dropped packet from %s: unexpected exception: (unknown)",fromAddr.toString().c_str());
  266. }
  267. }
  268. void Switch::onLocalEthernet(const SharedPtr<Network> &network,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  269. {
  270. SharedPtr<NetworkConfig> nconf(network->config2());
  271. if (!nconf)
  272. return;
  273. // Sanity check -- bridge loop? OS problem?
  274. if (to == network->mac())
  275. return;
  276. // Check to make sure this protocol is allowed on this network
  277. if (!nconf->permitsEtherType(etherType)) {
  278. TRACE("%.16llx: ignored tap: %s -> %s: ethertype %s not allowed on network %.16llx",network->id(),from.toString().c_str(),to.toString().c_str(),etherTypeName(etherType),(unsigned long long)network->id());
  279. return;
  280. }
  281. // Check if this packet is from someone other than the tap -- i.e. bridged in
  282. bool fromBridged = false;
  283. if (from != network->mac()) {
  284. if (!network->permitsBridging(RR->identity.address())) {
  285. TRACE("%.16llx: %s -> %s %s not forwarded, bridging disabled or this peer not a bridge",network->id(),from.toString().c_str(),to.toString().c_str(),etherTypeName(etherType));
  286. return;
  287. }
  288. fromBridged = true;
  289. }
  290. if (to.isMulticast()) {
  291. // Destination is a multicast address (including broadcast)
  292. MulticastGroup mg(to,0);
  293. if (to.isBroadcast()) {
  294. if ( (etherType == ZT_ETHERTYPE_ARP) && (len >= 28) && ((((const uint8_t *)data)[2] == 0x08)&&(((const uint8_t *)data)[3] == 0x00)&&(((const uint8_t *)data)[4] == 6)&&(((const uint8_t *)data)[5] == 4)&&(((const uint8_t *)data)[7] == 0x01)) ) {
  295. /* IPv4 ARP is one of the few special cases that we impose upon what is
  296. * otherwise a straightforward Ethernet switch emulation. Vanilla ARP
  297. * is dumb old broadcast and simply doesn't scale. ZeroTier multicast
  298. * groups have an additional field called ADI (additional distinguishing
  299. * information) which was added specifically for ARP though it could
  300. * be used for other things too. We then take ARP broadcasts and turn
  301. * them into multicasts by stuffing the IP address being queried into
  302. * the 32-bit ADI field. In practice this uses our multicast pub/sub
  303. * system to implement a kind of extended/distributed ARP table. */
  304. mg = MulticastGroup::deriveMulticastGroupForAddressResolution(InetAddress(((const unsigned char *)data) + 24,4,0));
  305. } else if (!nconf->enableBroadcast()) {
  306. // Don't transmit broadcasts if this network doesn't want them
  307. TRACE("%.16llx: dropped broadcast since ff:ff:ff:ff:ff:ff is not enabled",network->id());
  308. return;
  309. }
  310. } else if ((etherType == ZT_ETHERTYPE_IPV6)&&(len >= (40 + 8 + 16))) {
  311. /* IPv6 NDP emulation on ZeroTier-RFC4193 addressed networks! This allows
  312. * for multicast-free operation in IPv6 networks, which both improves
  313. * performance and is friendlier to mobile and (especially) IoT devices.
  314. * In the future there may be a no-multicast build option for embedded
  315. * and IoT use and this will be the preferred addressing mode. Note that
  316. * it plays nice with our L2 emulation philosophy and even with bridging.
  317. * While "real" devices behind the bridge can't have ZT-RFC4193 addresses
  318. * themselves, they can look these addresses up with NDP and it will
  319. * work just fine. */
  320. if ((reinterpret_cast<const uint8_t *>(data)[6] == 0x3a)&&(reinterpret_cast<const uint8_t *>(data)[40] == 0x87)) { // ICMPv6 neighbor solicitation
  321. for(std::vector<InetAddress>::const_iterator sip(nconf->staticIps().begin()),sipend(nconf->staticIps().end());sip!=sipend;++sip) {
  322. if ((sip->ss_family == AF_INET6)&&(Utils::ntoh((uint16_t)reinterpret_cast<const struct sockaddr_in6 *>(&(*sip))->sin6_port) == 88)) {
  323. const uint8_t *my6 = reinterpret_cast<const uint8_t *>(reinterpret_cast<const struct sockaddr_in6 *>(&(*sip))->sin6_addr.s6_addr);
  324. if ((my6[0] == 0xfd)&&(my6[9] == 0x99)&&(my6[10] == 0x93)) { // ZT-RFC4193 == fd__:____:____:____:__99:93__:____:____ / 88
  325. const uint8_t *pkt6 = reinterpret_cast<const uint8_t *>(data) + 40 + 8;
  326. unsigned int ptr = 0;
  327. while (ptr != 11) {
  328. if (pkt6[ptr] != my6[ptr])
  329. break;
  330. ++ptr;
  331. }
  332. if (ptr == 11) { // /88 matches an assigned address on this network
  333. const Address atPeer(pkt6 + ptr,5);
  334. if (atPeer != RR->identity.address()) {
  335. const MAC atPeerMac(atPeer,network->id());
  336. TRACE("ZT-RFC4193 NDP emulation: %.16llx: forging response for %s/%s",network->id(),atPeer.toString().c_str(),atPeerMac.toString().c_str());
  337. uint8_t adv[72];
  338. adv[0] = 0x60; adv[1] = 0x00; adv[2] = 0x00; adv[3] = 0x00;
  339. adv[4] = 0x00; adv[5] = 0x20;
  340. adv[6] = 0x3a; adv[7] = 0xff;
  341. for(int i=0;i<16;++i) adv[8 + i] = pkt6[i];
  342. for(int i=0;i<16;++i) adv[24 + i] = my6[i];
  343. adv[40] = 0x88; adv[41] = 0x00;
  344. adv[42] = 0x00; adv[43] = 0x00; // future home of checksum
  345. adv[44] = 0x60; adv[45] = 0x00; adv[46] = 0x00; adv[47] = 0x00;
  346. for(int i=0;i<16;++i) adv[48 + i] = pkt6[i];
  347. adv[64] = 0x02; adv[65] = 0x01;
  348. adv[66] = atPeerMac[0]; adv[67] = atPeerMac[1]; adv[68] = atPeerMac[2]; adv[69] = atPeerMac[3]; adv[70] = atPeerMac[4]; adv[71] = atPeerMac[5];
  349. uint16_t pseudo_[36];
  350. uint8_t *const pseudo = reinterpret_cast<uint8_t *>(pseudo_);
  351. for(int i=0;i<32;++i) pseudo[i] = adv[8 + i];
  352. pseudo[32] = 0x00; pseudo[33] = 0x00; pseudo[34] = 0x00; pseudo[35] = 0x20;
  353. pseudo[36] = 0x00; pseudo[37] = 0x00; pseudo[38] = 0x00; pseudo[39] = 0x3a;
  354. for(int i=0;i<32;++i) pseudo[40 + i] = adv[40 + i];
  355. uint32_t checksum = 0;
  356. for(int i=0;i<36;++i) checksum += Utils::hton(pseudo_[i]);
  357. while ((checksum >> 16)) checksum = (checksum & 0xffff) + (checksum >> 16);
  358. checksum = ~checksum;
  359. adv[42] = (checksum >> 8) & 0xff;
  360. adv[43] = checksum & 0xff;
  361. RR->node->putFrame(network->id(),network->userPtr(),atPeerMac,from,ZT_ETHERTYPE_IPV6,0,adv,72);
  362. return; // stop processing: we have handled this frame with a spoofed local reply so no need to send it anywhere
  363. }
  364. }
  365. }
  366. }
  367. }
  368. }
  369. }
  370. /* Learn multicast groups for bridged-in hosts.
  371. * Note that some OSes, most notably Linux, do this for you by learning
  372. * multicast addresses on bridge interfaces and subscribing each slave.
  373. * But in that case this does no harm, as the sets are just merged. */
  374. if (fromBridged)
  375. network->learnBridgedMulticastGroup(mg,RR->node->now());
  376. //TRACE("%.16llx: MULTICAST %s -> %s %s %u",network->id(),from.toString().c_str(),mg.toString().c_str(),etherTypeName(etherType),len);
  377. RR->mc->send(
  378. ((!nconf->isPublic())&&(nconf->com())) ? &(nconf->com()) : (const CertificateOfMembership *)0,
  379. nconf->multicastLimit(),
  380. RR->node->now(),
  381. network->id(),
  382. nconf->activeBridges(),
  383. mg,
  384. (fromBridged) ? from : MAC(),
  385. etherType,
  386. data,
  387. len);
  388. return;
  389. }
  390. if (to[0] == MAC::firstOctetForNetwork(network->id())) {
  391. // Destination is another ZeroTier peer on the same network
  392. Address toZT(to.toAddress(network->id())); // since in-network MACs are derived from addresses and network IDs, we can reverse this
  393. SharedPtr<Peer> toPeer(RR->topology->getPeer(toZT));
  394. const bool includeCom = ( (nconf->isPrivate()) && (nconf->com()) && ((!toPeer)||(toPeer->needsOurNetworkMembershipCertificate(network->id(),RR->node->now(),true))) );
  395. if ((fromBridged)||(includeCom)) {
  396. Packet outp(toZT,RR->identity.address(),Packet::VERB_EXT_FRAME);
  397. outp.append(network->id());
  398. if (includeCom) {
  399. outp.append((unsigned char)0x01); // 0x01 -- COM included
  400. nconf->com().serialize(outp);
  401. } else {
  402. outp.append((unsigned char)0x00);
  403. }
  404. to.appendTo(outp);
  405. from.appendTo(outp);
  406. outp.append((uint16_t)etherType);
  407. outp.append(data,len);
  408. outp.compress();
  409. send(outp,true,network->id());
  410. } else {
  411. Packet outp(toZT,RR->identity.address(),Packet::VERB_FRAME);
  412. outp.append(network->id());
  413. outp.append((uint16_t)etherType);
  414. outp.append(data,len);
  415. outp.compress();
  416. send(outp,true,network->id());
  417. }
  418. //TRACE("%.16llx: UNICAST: %s -> %s etherType==%s(%.4x) vlanId==%u len==%u fromBridged==%d includeCom==%d",network->id(),from.toString().c_str(),to.toString().c_str(),etherTypeName(etherType),etherType,vlanId,len,(int)fromBridged,(int)includeCom);
  419. return;
  420. }
  421. {
  422. // Destination is bridged behind a remote peer
  423. Address bridges[ZT_MAX_BRIDGE_SPAM];
  424. unsigned int numBridges = 0;
  425. /* Create an array of up to ZT_MAX_BRIDGE_SPAM recipients for this bridged frame. */
  426. bridges[0] = network->findBridgeTo(to);
  427. if ((bridges[0])&&(bridges[0] != RR->identity.address())&&(network->permitsBridging(bridges[0]))) {
  428. /* We have a known bridge route for this MAC, send it there. */
  429. ++numBridges;
  430. } else if (!nconf->activeBridges().empty()) {
  431. /* If there is no known route, spam to up to ZT_MAX_BRIDGE_SPAM active
  432. * bridges. If someone responds, we'll learn the route. */
  433. std::vector<Address>::const_iterator ab(nconf->activeBridges().begin());
  434. if (nconf->activeBridges().size() <= ZT_MAX_BRIDGE_SPAM) {
  435. // If there are <= ZT_MAX_BRIDGE_SPAM active bridges, spam them all
  436. while (ab != nconf->activeBridges().end()) {
  437. bridges[numBridges++] = *ab;
  438. ++ab;
  439. }
  440. } else {
  441. // Otherwise pick a random set of them
  442. while (numBridges < ZT_MAX_BRIDGE_SPAM) {
  443. if (ab == nconf->activeBridges().end())
  444. ab = nconf->activeBridges().begin();
  445. if (((unsigned long)RR->node->prng() % (unsigned long)nconf->activeBridges().size()) == 0) {
  446. bridges[numBridges++] = *ab;
  447. ++ab;
  448. } else ++ab;
  449. }
  450. }
  451. }
  452. for(unsigned int b=0;b<numBridges;++b) {
  453. SharedPtr<Peer> bridgePeer(RR->topology->getPeer(bridges[b]));
  454. Packet outp(bridges[b],RR->identity.address(),Packet::VERB_EXT_FRAME);
  455. outp.append(network->id());
  456. if ( (nconf->isPrivate()) && (nconf->com()) && ((!bridgePeer)||(bridgePeer->needsOurNetworkMembershipCertificate(network->id(),RR->node->now(),true))) ) {
  457. outp.append((unsigned char)0x01); // 0x01 -- COM included
  458. nconf->com().serialize(outp);
  459. } else {
  460. outp.append((unsigned char)0);
  461. }
  462. to.appendTo(outp);
  463. from.appendTo(outp);
  464. outp.append((uint16_t)etherType);
  465. outp.append(data,len);
  466. outp.compress();
  467. send(outp,true,network->id());
  468. }
  469. }
  470. }
  471. void Switch::send(const Packet &packet,bool encrypt,uint64_t nwid)
  472. {
  473. if (packet.destination() == RR->identity.address()) {
  474. TRACE("BUG: caught attempt to send() to self, ignored");
  475. return;
  476. }
  477. //TRACE(">> %s to %s (%u bytes, encrypt==%d, nwid==%.16llx)",Packet::verbString(packet.verb()),packet.destination().toString().c_str(),packet.size(),(int)encrypt,nwid);
  478. if (!_trySend(packet,encrypt,nwid)) {
  479. Mutex::Lock _l(_txQueue_m);
  480. _txQueue.push_back(TXQueueEntry(packet.destination(),RR->node->now(),packet,encrypt,nwid));
  481. }
  482. }
  483. bool Switch::unite(const Address &p1,const Address &p2)
  484. {
  485. if ((p1 == RR->identity.address())||(p2 == RR->identity.address()))
  486. return false;
  487. SharedPtr<Peer> p1p = RR->topology->getPeer(p1);
  488. if (!p1p)
  489. return false;
  490. SharedPtr<Peer> p2p = RR->topology->getPeer(p2);
  491. if (!p2p)
  492. return false;
  493. const uint64_t now = RR->node->now();
  494. std::pair<InetAddress,InetAddress> cg(Peer::findCommonGround(*p1p,*p2p,now));
  495. if ((!(cg.first))||(cg.first.ipScope() != cg.second.ipScope()))
  496. return false;
  497. TRACE("unite: %s(%s) <> %s(%s)",p1.toString().c_str(),cg.second.toString().c_str(),p2.toString().c_str(),cg.first.toString().c_str());
  498. /* Tell P1 where to find P2 and vice versa, sending the packets to P1 and
  499. * P2 in randomized order in terms of which gets sent first. This is done
  500. * since in a few cases NAT-t can be sensitive to slight timing differences
  501. * in terms of when the two peers initiate. Normally this is accounted for
  502. * by the nearly-simultaneous RENDEZVOUS kickoff from the relay, but
  503. * given that relay are hosted on cloud providers this can in some
  504. * cases have a few ms of latency between packet departures. By randomizing
  505. * the order we make each attempted NAT-t favor one or the other going
  506. * first, meaning if it doesn't succeed the first time it might the second
  507. * and so forth. */
  508. unsigned int alt = (unsigned int)RR->node->prng() & 1;
  509. unsigned int completed = alt + 2;
  510. while (alt != completed) {
  511. if ((alt & 1) == 0) {
  512. // Tell p1 where to find p2.
  513. Packet outp(p1,RR->identity.address(),Packet::VERB_RENDEZVOUS);
  514. outp.append((unsigned char)0);
  515. p2.appendTo(outp);
  516. outp.append((uint16_t)cg.first.port());
  517. if (cg.first.isV6()) {
  518. outp.append((unsigned char)16);
  519. outp.append(cg.first.rawIpData(),16);
  520. } else {
  521. outp.append((unsigned char)4);
  522. outp.append(cg.first.rawIpData(),4);
  523. }
  524. outp.armor(p1p->key(),true);
  525. p1p->send(outp.data(),outp.size(),now);
  526. } else {
  527. // Tell p2 where to find p1.
  528. Packet outp(p2,RR->identity.address(),Packet::VERB_RENDEZVOUS);
  529. outp.append((unsigned char)0);
  530. p1.appendTo(outp);
  531. outp.append((uint16_t)cg.second.port());
  532. if (cg.second.isV6()) {
  533. outp.append((unsigned char)16);
  534. outp.append(cg.second.rawIpData(),16);
  535. } else {
  536. outp.append((unsigned char)4);
  537. outp.append(cg.second.rawIpData(),4);
  538. }
  539. outp.armor(p2p->key(),true);
  540. p2p->send(outp.data(),outp.size(),now);
  541. }
  542. ++alt; // counts up and also flips LSB
  543. }
  544. return true;
  545. }
  546. void Switch::rendezvous(const SharedPtr<Peer> &peer,const InetAddress &localAddr,const InetAddress &atAddr)
  547. {
  548. TRACE("sending NAT-t message to %s(%s)",peer->address().toString().c_str(),atAddr.toString().c_str());
  549. const uint64_t now = RR->node->now();
  550. peer->sendHELLO(localAddr,atAddr,now,2); // first attempt: send low-TTL packet to 'open' local NAT
  551. {
  552. Mutex::Lock _l(_contactQueue_m);
  553. _contactQueue.push_back(ContactQueueEntry(peer,now + ZT_NAT_T_TACTICAL_ESCALATION_DELAY,localAddr,atAddr));
  554. }
  555. }
  556. void Switch::requestWhois(const Address &addr)
  557. {
  558. bool inserted = false;
  559. {
  560. Mutex::Lock _l(_outstandingWhoisRequests_m);
  561. WhoisRequest &r = _outstandingWhoisRequests[addr];
  562. if (r.lastSent) {
  563. r.retries = 0; // reset retry count if entry already existed, but keep waiting and retry again after normal timeout
  564. } else {
  565. r.lastSent = RR->node->now();
  566. inserted = true;
  567. }
  568. }
  569. if (inserted)
  570. _sendWhoisRequest(addr,(const Address *)0,0);
  571. }
  572. void Switch::doAnythingWaitingForPeer(const SharedPtr<Peer> &peer)
  573. {
  574. { // cancel pending WHOIS since we now know this peer
  575. Mutex::Lock _l(_outstandingWhoisRequests_m);
  576. _outstandingWhoisRequests.erase(peer->address());
  577. }
  578. { // finish processing any packets waiting on peer's public key / identity
  579. Mutex::Lock _l(_rxQueue_m);
  580. unsigned long i = ZT_RX_QUEUE_SIZE;
  581. while (i) {
  582. RXQueueEntry *rq = &(_rxQueue[--i]);
  583. if ((rq->timestamp)&&(rq->complete)) {
  584. if (rq->frag0.tryDecode(RR,false))
  585. rq->timestamp = 0;
  586. }
  587. }
  588. }
  589. { // finish sending any packets waiting on peer's public key / identity
  590. Mutex::Lock _l(_txQueue_m);
  591. for(std::list< TXQueueEntry >::iterator txi(_txQueue.begin());txi!=_txQueue.end();) {
  592. if (txi->dest == peer->address()) {
  593. if (_trySend(txi->packet,txi->encrypt,txi->nwid))
  594. _txQueue.erase(txi++);
  595. else ++txi;
  596. } else ++txi;
  597. }
  598. }
  599. }
  600. unsigned long Switch::doTimerTasks(uint64_t now)
  601. {
  602. unsigned long nextDelay = 0xffffffff; // ceiling delay, caller will cap to minimum
  603. { // Iterate through NAT traversal strategies for entries in contact queue
  604. Mutex::Lock _l(_contactQueue_m);
  605. for(std::list<ContactQueueEntry>::iterator qi(_contactQueue.begin());qi!=_contactQueue.end();) {
  606. if (now >= qi->fireAtTime) {
  607. if (!qi->peer->pushDirectPaths(qi->localAddr,qi->inaddr,now,true))
  608. qi->peer->sendHELLO(qi->localAddr,qi->inaddr,now);
  609. _contactQueue.erase(qi++);
  610. continue;
  611. /* Old symmetric NAT buster code, obsoleted by port prediction alg in SelfAwareness but left around for now in case we revert
  612. if (qi->strategyIteration == 0) {
  613. // First strategy: send packet directly to destination
  614. qi->peer->sendHELLO(qi->localAddr,qi->inaddr,now);
  615. } else if (qi->strategyIteration <= 3) {
  616. // Strategies 1-3: try escalating ports for symmetric NATs that remap sequentially
  617. InetAddress tmpaddr(qi->inaddr);
  618. int p = (int)qi->inaddr.port() + qi->strategyIteration;
  619. if (p > 65535)
  620. p -= 64511;
  621. tmpaddr.setPort((unsigned int)p);
  622. qi->peer->sendHELLO(qi->localAddr,tmpaddr,now);
  623. } else {
  624. // All strategies tried, expire entry
  625. _contactQueue.erase(qi++);
  626. continue;
  627. }
  628. ++qi->strategyIteration;
  629. qi->fireAtTime = now + ZT_NAT_T_TACTICAL_ESCALATION_DELAY;
  630. nextDelay = std::min(nextDelay,(unsigned long)ZT_NAT_T_TACTICAL_ESCALATION_DELAY);
  631. */
  632. } else {
  633. nextDelay = std::min(nextDelay,(unsigned long)(qi->fireAtTime - now));
  634. }
  635. ++qi; // if qi was erased, loop will have continued before here
  636. }
  637. }
  638. { // Retry outstanding WHOIS requests
  639. Mutex::Lock _l(_outstandingWhoisRequests_m);
  640. Hashtable< Address,WhoisRequest >::Iterator i(_outstandingWhoisRequests);
  641. Address *a = (Address *)0;
  642. WhoisRequest *r = (WhoisRequest *)0;
  643. while (i.next(a,r)) {
  644. const unsigned long since = (unsigned long)(now - r->lastSent);
  645. if (since >= ZT_WHOIS_RETRY_DELAY) {
  646. if (r->retries >= ZT_MAX_WHOIS_RETRIES) {
  647. TRACE("WHOIS %s timed out",a->toString().c_str());
  648. _outstandingWhoisRequests.erase(*a);
  649. } else {
  650. r->lastSent = now;
  651. r->peersConsulted[r->retries] = _sendWhoisRequest(*a,r->peersConsulted,r->retries);
  652. ++r->retries;
  653. TRACE("WHOIS %s (retry %u)",a->toString().c_str(),r->retries);
  654. nextDelay = std::min(nextDelay,(unsigned long)ZT_WHOIS_RETRY_DELAY);
  655. }
  656. } else {
  657. nextDelay = std::min(nextDelay,ZT_WHOIS_RETRY_DELAY - since);
  658. }
  659. }
  660. }
  661. { // Time out TX queue packets that never got WHOIS lookups or other info.
  662. Mutex::Lock _l(_txQueue_m);
  663. for(std::list< TXQueueEntry >::iterator txi(_txQueue.begin());txi!=_txQueue.end();) {
  664. if (_trySend(txi->packet,txi->encrypt,txi->nwid))
  665. _txQueue.erase(txi++);
  666. else if ((now - txi->creationTime) > ZT_TRANSMIT_QUEUE_TIMEOUT) {
  667. TRACE("TX %s -> %s timed out",txi->packet.source().toString().c_str(),txi->packet.destination().toString().c_str());
  668. _txQueue.erase(txi++);
  669. } else ++txi;
  670. }
  671. }
  672. { // Remove really old last unite attempt entries to keep table size controlled
  673. Mutex::Lock _l(_lastUniteAttempt_m);
  674. Hashtable< _LastUniteKey,uint64_t >::Iterator i(_lastUniteAttempt);
  675. _LastUniteKey *k = (_LastUniteKey *)0;
  676. uint64_t *v = (uint64_t *)0;
  677. while (i.next(k,v)) {
  678. if ((now - *v) >= (ZT_MIN_UNITE_INTERVAL * 8))
  679. _lastUniteAttempt.erase(*k);
  680. }
  681. }
  682. return nextDelay;
  683. }
  684. Address Switch::_sendWhoisRequest(const Address &addr,const Address *peersAlreadyConsulted,unsigned int numPeersAlreadyConsulted)
  685. {
  686. SharedPtr<Peer> root(RR->topology->getBestRoot(peersAlreadyConsulted,numPeersAlreadyConsulted,false));
  687. if (root) {
  688. Packet outp(root->address(),RR->identity.address(),Packet::VERB_WHOIS);
  689. addr.appendTo(outp);
  690. outp.armor(root->key(),true);
  691. if (root->send(outp.data(),outp.size(),RR->node->now()))
  692. return root->address();
  693. }
  694. return Address();
  695. }
  696. bool Switch::_trySend(const Packet &packet,bool encrypt,uint64_t nwid)
  697. {
  698. SharedPtr<Peer> peer(RR->topology->getPeer(packet.destination()));
  699. if (peer) {
  700. const uint64_t now = RR->node->now();
  701. SharedPtr<Network> network;
  702. SharedPtr<NetworkConfig> nconf;
  703. if (nwid) {
  704. network = RR->node->network(nwid);
  705. if (!network)
  706. return false; // we probably just left this network, let its packets die
  707. nconf = network->config2();
  708. if (!nconf)
  709. return false; // sanity check: unconfigured network? why are we trying to talk to it?
  710. }
  711. Path *viaPath = peer->getBestPath(now);
  712. SharedPtr<Peer> relay;
  713. if (!viaPath) {
  714. // See if this network has a preferred relay (if packet has an associated network)
  715. if (nconf) {
  716. unsigned int bestq = ~((unsigned int)0);
  717. for(std::vector< std::pair<Address,InetAddress> >::const_iterator r(nconf->relays().begin());r!=nconf->relays().end();++r) {
  718. if (r->first != peer->address()) {
  719. SharedPtr<Peer> rp(RR->topology->getPeer(r->first));
  720. if (rp) {
  721. const unsigned int q = rp->relayQuality(now);
  722. if (q < bestq) { // SUBTILE: < == don't use these if they are nil quality (unsigned int max), instead use a root
  723. bestq = q;
  724. rp.swap(relay);
  725. }
  726. }
  727. }
  728. }
  729. }
  730. // Otherwise relay off a root server
  731. if (!relay)
  732. relay = RR->topology->getBestRoot();
  733. if (!(relay)||(!(viaPath = relay->getBestPath(now))))
  734. return false; // no paths, no root servers?, no relays? :P~~~
  735. }
  736. if ((network)&&(relay)&&(network->isAllowed(peer))) {
  737. // Push hints for direct connectivity to this peer if we are relaying
  738. peer->pushDirectPaths(viaPath->localAddress(),viaPath->address(),now,false);
  739. viaPath->sent(now);
  740. }
  741. Packet tmp(packet);
  742. unsigned int chunkSize = std::min(tmp.size(),(unsigned int)ZT_UDP_DEFAULT_PAYLOAD_MTU);
  743. tmp.setFragmented(chunkSize < tmp.size());
  744. tmp.armor(peer->key(),encrypt);
  745. if (viaPath->send(RR,tmp.data(),chunkSize,now)) {
  746. if (chunkSize < tmp.size()) {
  747. // Too big for one packet, fragment the rest
  748. unsigned int fragStart = chunkSize;
  749. unsigned int remaining = tmp.size() - chunkSize;
  750. unsigned int fragsRemaining = (remaining / (ZT_UDP_DEFAULT_PAYLOAD_MTU - ZT_PROTO_MIN_FRAGMENT_LENGTH));
  751. if ((fragsRemaining * (ZT_UDP_DEFAULT_PAYLOAD_MTU - ZT_PROTO_MIN_FRAGMENT_LENGTH)) < remaining)
  752. ++fragsRemaining;
  753. unsigned int totalFragments = fragsRemaining + 1;
  754. for(unsigned int fno=1;fno<totalFragments;++fno) {
  755. chunkSize = std::min(remaining,(unsigned int)(ZT_UDP_DEFAULT_PAYLOAD_MTU - ZT_PROTO_MIN_FRAGMENT_LENGTH));
  756. Packet::Fragment frag(tmp,fragStart,chunkSize,fno,totalFragments);
  757. viaPath->send(RR,frag.data(),frag.size(),now);
  758. fragStart += chunkSize;
  759. remaining -= chunkSize;
  760. }
  761. }
  762. return true;
  763. }
  764. } else {
  765. requestWhois(packet.destination());
  766. }
  767. return false;
  768. }
  769. } // namespace ZeroTier