Switch.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  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. if (!network->hasConfig())
  271. return;
  272. // Sanity check -- bridge loop? OS problem?
  273. if (to == network->mac())
  274. return;
  275. // Check to make sure this protocol is allowed on this network
  276. if (!network->config().permitsEtherType(etherType)) {
  277. 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());
  278. return;
  279. }
  280. // Check if this packet is from someone other than the tap -- i.e. bridged in
  281. bool fromBridged = false;
  282. if (from != network->mac()) {
  283. if (!network->config().permitsBridging(RR->identity.address())) {
  284. 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));
  285. return;
  286. }
  287. fromBridged = true;
  288. }
  289. if (to.isMulticast()) {
  290. // Destination is a multicast address (including broadcast)
  291. MulticastGroup mg(to,0);
  292. if (to.isBroadcast()) {
  293. 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)) ) {
  294. /* IPv4 ARP is one of the few special cases that we impose upon what is
  295. * otherwise a straightforward Ethernet switch emulation. Vanilla ARP
  296. * is dumb old broadcast and simply doesn't scale. ZeroTier multicast
  297. * groups have an additional field called ADI (additional distinguishing
  298. * information) which was added specifically for ARP though it could
  299. * be used for other things too. We then take ARP broadcasts and turn
  300. * them into multicasts by stuffing the IP address being queried into
  301. * the 32-bit ADI field. In practice this uses our multicast pub/sub
  302. * system to implement a kind of extended/distributed ARP table. */
  303. mg = MulticastGroup::deriveMulticastGroupForAddressResolution(InetAddress(((const unsigned char *)data) + 24,4,0));
  304. } else if (!network->config().enableBroadcast()) {
  305. // Don't transmit broadcasts if this network doesn't want them
  306. TRACE("%.16llx: dropped broadcast since ff:ff:ff:ff:ff:ff is not enabled",network->id());
  307. return;
  308. }
  309. } else if ((etherType == ZT_ETHERTYPE_IPV6)&&(len >= (40 + 8 + 16))) {
  310. /* IPv6 NDP emulation on ZeroTier-RFC4193 addressed networks! This allows
  311. * for multicast-free operation in IPv6 networks, which both improves
  312. * performance and is friendlier to mobile and (especially) IoT devices.
  313. * In the future there may be a no-multicast build option for embedded
  314. * and IoT use and this will be the preferred addressing mode. Note that
  315. * it plays nice with our L2 emulation philosophy and even with bridging.
  316. * While "real" devices behind the bridge can't have ZT-RFC4193 addresses
  317. * themselves, they can look these addresses up with NDP and it will
  318. * work just fine. */
  319. if ((reinterpret_cast<const uint8_t *>(data)[6] == 0x3a)&&(reinterpret_cast<const uint8_t *>(data)[40] == 0x87)) { // ICMPv6 neighbor solicitation
  320. std::vector<InetAddress> sips(network->config().staticIps());
  321. for(std::vector<InetAddress>::const_iterator sip(sips.begin());sip!=sips.end();++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. ((!network->config().isPublic())&&(network->config().com())) ? &(network->config().com()) : (const CertificateOfMembership *)0,
  379. network->config().multicastLimit(),
  380. RR->node->now(),
  381. network->id(),
  382. network->config().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 = ( (network->config().isPrivate()) && (network->config().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. network->config().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. std::vector<Address> activeBridges(network->config().activeBridges());
  428. if ((bridges[0])&&(bridges[0] != RR->identity.address())&&(network->config().permitsBridging(bridges[0]))) {
  429. /* We have a known bridge route for this MAC, send it there. */
  430. ++numBridges;
  431. } else if (!activeBridges.empty()) {
  432. /* If there is no known route, spam to up to ZT_MAX_BRIDGE_SPAM active
  433. * bridges. If someone responds, we'll learn the route. */
  434. std::vector<Address>::const_iterator ab(activeBridges.begin());
  435. if (activeBridges.size() <= ZT_MAX_BRIDGE_SPAM) {
  436. // If there are <= ZT_MAX_BRIDGE_SPAM active bridges, spam them all
  437. while (ab != activeBridges.end()) {
  438. bridges[numBridges++] = *ab;
  439. ++ab;
  440. }
  441. } else {
  442. // Otherwise pick a random set of them
  443. while (numBridges < ZT_MAX_BRIDGE_SPAM) {
  444. if (ab == activeBridges.end())
  445. ab = activeBridges.begin();
  446. if (((unsigned long)RR->node->prng() % (unsigned long)activeBridges.size()) == 0) {
  447. bridges[numBridges++] = *ab;
  448. ++ab;
  449. } else ++ab;
  450. }
  451. }
  452. }
  453. for(unsigned int b=0;b<numBridges;++b) {
  454. SharedPtr<Peer> bridgePeer(RR->topology->getPeer(bridges[b]));
  455. Packet outp(bridges[b],RR->identity.address(),Packet::VERB_EXT_FRAME);
  456. outp.append(network->id());
  457. if ( (network->config().isPrivate()) && (network->config().com()) && ((!bridgePeer)||(bridgePeer->needsOurNetworkMembershipCertificate(network->id(),RR->node->now(),true))) ) {
  458. outp.append((unsigned char)0x01); // 0x01 -- COM included
  459. network->config().com().serialize(outp);
  460. } else {
  461. outp.append((unsigned char)0);
  462. }
  463. to.appendTo(outp);
  464. from.appendTo(outp);
  465. outp.append((uint16_t)etherType);
  466. outp.append(data,len);
  467. outp.compress();
  468. send(outp,true,network->id());
  469. }
  470. }
  471. }
  472. void Switch::send(const Packet &packet,bool encrypt,uint64_t nwid)
  473. {
  474. if (packet.destination() == RR->identity.address()) {
  475. TRACE("BUG: caught attempt to send() to self, ignored");
  476. return;
  477. }
  478. //TRACE(">> %s to %s (%u bytes, encrypt==%d, nwid==%.16llx)",Packet::verbString(packet.verb()),packet.destination().toString().c_str(),packet.size(),(int)encrypt,nwid);
  479. if (!_trySend(packet,encrypt,nwid)) {
  480. Mutex::Lock _l(_txQueue_m);
  481. _txQueue.push_back(TXQueueEntry(packet.destination(),RR->node->now(),packet,encrypt,nwid));
  482. }
  483. }
  484. bool Switch::unite(const Address &p1,const Address &p2)
  485. {
  486. if ((p1 == RR->identity.address())||(p2 == RR->identity.address()))
  487. return false;
  488. SharedPtr<Peer> p1p = RR->topology->getPeer(p1);
  489. if (!p1p)
  490. return false;
  491. SharedPtr<Peer> p2p = RR->topology->getPeer(p2);
  492. if (!p2p)
  493. return false;
  494. const uint64_t now = RR->node->now();
  495. std::pair<InetAddress,InetAddress> cg(Peer::findCommonGround(*p1p,*p2p,now));
  496. if ((!(cg.first))||(cg.first.ipScope() != cg.second.ipScope()))
  497. return false;
  498. TRACE("unite: %s(%s) <> %s(%s)",p1.toString().c_str(),cg.second.toString().c_str(),p2.toString().c_str(),cg.first.toString().c_str());
  499. /* Tell P1 where to find P2 and vice versa, sending the packets to P1 and
  500. * P2 in randomized order in terms of which gets sent first. This is done
  501. * since in a few cases NAT-t can be sensitive to slight timing differences
  502. * in terms of when the two peers initiate. Normally this is accounted for
  503. * by the nearly-simultaneous RENDEZVOUS kickoff from the relay, but
  504. * given that relay are hosted on cloud providers this can in some
  505. * cases have a few ms of latency between packet departures. By randomizing
  506. * the order we make each attempted NAT-t favor one or the other going
  507. * first, meaning if it doesn't succeed the first time it might the second
  508. * and so forth. */
  509. unsigned int alt = (unsigned int)RR->node->prng() & 1;
  510. unsigned int completed = alt + 2;
  511. while (alt != completed) {
  512. if ((alt & 1) == 0) {
  513. // Tell p1 where to find p2.
  514. Packet outp(p1,RR->identity.address(),Packet::VERB_RENDEZVOUS);
  515. outp.append((unsigned char)0);
  516. p2.appendTo(outp);
  517. outp.append((uint16_t)cg.first.port());
  518. if (cg.first.isV6()) {
  519. outp.append((unsigned char)16);
  520. outp.append(cg.first.rawIpData(),16);
  521. } else {
  522. outp.append((unsigned char)4);
  523. outp.append(cg.first.rawIpData(),4);
  524. }
  525. outp.armor(p1p->key(),true);
  526. p1p->send(outp.data(),outp.size(),now);
  527. } else {
  528. // Tell p2 where to find p1.
  529. Packet outp(p2,RR->identity.address(),Packet::VERB_RENDEZVOUS);
  530. outp.append((unsigned char)0);
  531. p1.appendTo(outp);
  532. outp.append((uint16_t)cg.second.port());
  533. if (cg.second.isV6()) {
  534. outp.append((unsigned char)16);
  535. outp.append(cg.second.rawIpData(),16);
  536. } else {
  537. outp.append((unsigned char)4);
  538. outp.append(cg.second.rawIpData(),4);
  539. }
  540. outp.armor(p2p->key(),true);
  541. p2p->send(outp.data(),outp.size(),now);
  542. }
  543. ++alt; // counts up and also flips LSB
  544. }
  545. return true;
  546. }
  547. void Switch::rendezvous(const SharedPtr<Peer> &peer,const InetAddress &localAddr,const InetAddress &atAddr)
  548. {
  549. TRACE("sending NAT-t message to %s(%s)",peer->address().toString().c_str(),atAddr.toString().c_str());
  550. const uint64_t now = RR->node->now();
  551. peer->sendHELLO(localAddr,atAddr,now,2); // first attempt: send low-TTL packet to 'open' local NAT
  552. {
  553. Mutex::Lock _l(_contactQueue_m);
  554. _contactQueue.push_back(ContactQueueEntry(peer,now + ZT_NAT_T_TACTICAL_ESCALATION_DELAY,localAddr,atAddr));
  555. }
  556. }
  557. void Switch::requestWhois(const Address &addr)
  558. {
  559. bool inserted = false;
  560. {
  561. Mutex::Lock _l(_outstandingWhoisRequests_m);
  562. WhoisRequest &r = _outstandingWhoisRequests[addr];
  563. if (r.lastSent) {
  564. r.retries = 0; // reset retry count if entry already existed, but keep waiting and retry again after normal timeout
  565. } else {
  566. r.lastSent = RR->node->now();
  567. inserted = true;
  568. }
  569. }
  570. if (inserted)
  571. _sendWhoisRequest(addr,(const Address *)0,0);
  572. }
  573. void Switch::doAnythingWaitingForPeer(const SharedPtr<Peer> &peer)
  574. {
  575. { // cancel pending WHOIS since we now know this peer
  576. Mutex::Lock _l(_outstandingWhoisRequests_m);
  577. _outstandingWhoisRequests.erase(peer->address());
  578. }
  579. { // finish processing any packets waiting on peer's public key / identity
  580. Mutex::Lock _l(_rxQueue_m);
  581. unsigned long i = ZT_RX_QUEUE_SIZE;
  582. while (i) {
  583. RXQueueEntry *rq = &(_rxQueue[--i]);
  584. if ((rq->timestamp)&&(rq->complete)) {
  585. if (rq->frag0.tryDecode(RR,false))
  586. rq->timestamp = 0;
  587. }
  588. }
  589. }
  590. { // finish sending any packets waiting on peer's public key / identity
  591. Mutex::Lock _l(_txQueue_m);
  592. for(std::list< TXQueueEntry >::iterator txi(_txQueue.begin());txi!=_txQueue.end();) {
  593. if (txi->dest == peer->address()) {
  594. if (_trySend(txi->packet,txi->encrypt,txi->nwid))
  595. _txQueue.erase(txi++);
  596. else ++txi;
  597. } else ++txi;
  598. }
  599. }
  600. }
  601. unsigned long Switch::doTimerTasks(uint64_t now)
  602. {
  603. unsigned long nextDelay = 0xffffffff; // ceiling delay, caller will cap to minimum
  604. { // Iterate through NAT traversal strategies for entries in contact queue
  605. Mutex::Lock _l(_contactQueue_m);
  606. for(std::list<ContactQueueEntry>::iterator qi(_contactQueue.begin());qi!=_contactQueue.end();) {
  607. if (now >= qi->fireAtTime) {
  608. if (!qi->peer->pushDirectPaths(qi->localAddr,qi->inaddr,now,true,false))
  609. qi->peer->sendHELLO(qi->localAddr,qi->inaddr,now);
  610. _contactQueue.erase(qi++);
  611. continue;
  612. /* Old symmetric NAT buster code, obsoleted by port prediction alg in SelfAwareness but left around for now in case we revert
  613. if (qi->strategyIteration == 0) {
  614. // First strategy: send packet directly to destination
  615. qi->peer->sendHELLO(qi->localAddr,qi->inaddr,now);
  616. } else if (qi->strategyIteration <= 3) {
  617. // Strategies 1-3: try escalating ports for symmetric NATs that remap sequentially
  618. InetAddress tmpaddr(qi->inaddr);
  619. int p = (int)qi->inaddr.port() + qi->strategyIteration;
  620. if (p > 65535)
  621. p -= 64511;
  622. tmpaddr.setPort((unsigned int)p);
  623. qi->peer->sendHELLO(qi->localAddr,tmpaddr,now);
  624. } else {
  625. // All strategies tried, expire entry
  626. _contactQueue.erase(qi++);
  627. continue;
  628. }
  629. ++qi->strategyIteration;
  630. qi->fireAtTime = now + ZT_NAT_T_TACTICAL_ESCALATION_DELAY;
  631. nextDelay = std::min(nextDelay,(unsigned long)ZT_NAT_T_TACTICAL_ESCALATION_DELAY);
  632. */
  633. } else {
  634. nextDelay = std::min(nextDelay,(unsigned long)(qi->fireAtTime - now));
  635. }
  636. ++qi; // if qi was erased, loop will have continued before here
  637. }
  638. }
  639. { // Retry outstanding WHOIS requests
  640. Mutex::Lock _l(_outstandingWhoisRequests_m);
  641. Hashtable< Address,WhoisRequest >::Iterator i(_outstandingWhoisRequests);
  642. Address *a = (Address *)0;
  643. WhoisRequest *r = (WhoisRequest *)0;
  644. while (i.next(a,r)) {
  645. const unsigned long since = (unsigned long)(now - r->lastSent);
  646. if (since >= ZT_WHOIS_RETRY_DELAY) {
  647. if (r->retries >= ZT_MAX_WHOIS_RETRIES) {
  648. TRACE("WHOIS %s timed out",a->toString().c_str());
  649. _outstandingWhoisRequests.erase(*a);
  650. } else {
  651. r->lastSent = now;
  652. r->peersConsulted[r->retries] = _sendWhoisRequest(*a,r->peersConsulted,r->retries);
  653. ++r->retries;
  654. TRACE("WHOIS %s (retry %u)",a->toString().c_str(),r->retries);
  655. nextDelay = std::min(nextDelay,(unsigned long)ZT_WHOIS_RETRY_DELAY);
  656. }
  657. } else {
  658. nextDelay = std::min(nextDelay,ZT_WHOIS_RETRY_DELAY - since);
  659. }
  660. }
  661. }
  662. { // Time out TX queue packets that never got WHOIS lookups or other info.
  663. Mutex::Lock _l(_txQueue_m);
  664. for(std::list< TXQueueEntry >::iterator txi(_txQueue.begin());txi!=_txQueue.end();) {
  665. if (_trySend(txi->packet,txi->encrypt,txi->nwid))
  666. _txQueue.erase(txi++);
  667. else if ((now - txi->creationTime) > ZT_TRANSMIT_QUEUE_TIMEOUT) {
  668. TRACE("TX %s -> %s timed out",txi->packet.source().toString().c_str(),txi->packet.destination().toString().c_str());
  669. _txQueue.erase(txi++);
  670. } else ++txi;
  671. }
  672. }
  673. { // Remove really old last unite attempt entries to keep table size controlled
  674. Mutex::Lock _l(_lastUniteAttempt_m);
  675. Hashtable< _LastUniteKey,uint64_t >::Iterator i(_lastUniteAttempt);
  676. _LastUniteKey *k = (_LastUniteKey *)0;
  677. uint64_t *v = (uint64_t *)0;
  678. while (i.next(k,v)) {
  679. if ((now - *v) >= (ZT_MIN_UNITE_INTERVAL * 8))
  680. _lastUniteAttempt.erase(*k);
  681. }
  682. }
  683. return nextDelay;
  684. }
  685. Address Switch::_sendWhoisRequest(const Address &addr,const Address *peersAlreadyConsulted,unsigned int numPeersAlreadyConsulted)
  686. {
  687. SharedPtr<Peer> root(RR->topology->getBestRoot(peersAlreadyConsulted,numPeersAlreadyConsulted,false));
  688. if (root) {
  689. Packet outp(root->address(),RR->identity.address(),Packet::VERB_WHOIS);
  690. addr.appendTo(outp);
  691. outp.armor(root->key(),true);
  692. if (root->send(outp.data(),outp.size(),RR->node->now()))
  693. return root->address();
  694. }
  695. return Address();
  696. }
  697. bool Switch::_trySend(const Packet &packet,bool encrypt,uint64_t nwid)
  698. {
  699. SharedPtr<Peer> peer(RR->topology->getPeer(packet.destination()));
  700. if (peer) {
  701. const uint64_t now = RR->node->now();
  702. SharedPtr<Network> network;
  703. if (nwid) {
  704. network = RR->node->network(nwid);
  705. if ((!network)||(!network->hasConfig()))
  706. return false; // we probably just left this network, let its packets die
  707. }
  708. Path *viaPath = peer->getBestPath(now);
  709. SharedPtr<Peer> relay;
  710. if (!viaPath) {
  711. if (network) {
  712. unsigned int bestq = ~((unsigned int)0); // max unsigned int since quality is lower==better
  713. for(unsigned int ri=0;ri<network->config().staticDeviceCount();++ri) {
  714. const ZT_VirtualNetworkStaticDevice &r = network->config().staticDevice(ri);
  715. if ((r.address != peer->address().toInt())&&((r.flags & ZT_NETWORK_STATIC_DEVICE_IS_RELAY) != 0)) {
  716. SharedPtr<Peer> rp(RR->topology->getPeer(Address(r.address)));
  717. if (rp) {
  718. const unsigned int q = rp->relayQuality(now);
  719. if (q < bestq) {
  720. bestq = q;
  721. rp.swap(relay);
  722. }
  723. }
  724. }
  725. }
  726. }
  727. if (!relay)
  728. relay = RR->topology->getBestRoot();
  729. if ( (!relay) || (!(viaPath = relay->getBestPath(now))) )
  730. return false;
  731. }
  732. // viaPath will not be null if we make it here
  733. // Push possible direct paths to us if we are relaying
  734. if (relay) {
  735. peer->pushDirectPaths(viaPath->localAddress(),viaPath->address(),now,false,( (network)&&(network->isAllowed(peer)) ));
  736. viaPath->sent(now);
  737. }
  738. Packet tmp(packet);
  739. unsigned int chunkSize = std::min(tmp.size(),(unsigned int)ZT_UDP_DEFAULT_PAYLOAD_MTU);
  740. tmp.setFragmented(chunkSize < tmp.size());
  741. tmp.armor(peer->key(),encrypt);
  742. if (viaPath->send(RR,tmp.data(),chunkSize,now)) {
  743. if (chunkSize < tmp.size()) {
  744. // Too big for one packet, fragment the rest
  745. unsigned int fragStart = chunkSize;
  746. unsigned int remaining = tmp.size() - chunkSize;
  747. unsigned int fragsRemaining = (remaining / (ZT_UDP_DEFAULT_PAYLOAD_MTU - ZT_PROTO_MIN_FRAGMENT_LENGTH));
  748. if ((fragsRemaining * (ZT_UDP_DEFAULT_PAYLOAD_MTU - ZT_PROTO_MIN_FRAGMENT_LENGTH)) < remaining)
  749. ++fragsRemaining;
  750. unsigned int totalFragments = fragsRemaining + 1;
  751. for(unsigned int fno=1;fno<totalFragments;++fno) {
  752. chunkSize = std::min(remaining,(unsigned int)(ZT_UDP_DEFAULT_PAYLOAD_MTU - ZT_PROTO_MIN_FRAGMENT_LENGTH));
  753. Packet::Fragment frag(tmp,fragStart,chunkSize,fno,totalFragments);
  754. viaPath->send(RR,frag.data(),frag.size(),now);
  755. fragStart += chunkSize;
  756. remaining -= chunkSize;
  757. }
  758. }
  759. return true;
  760. }
  761. } else {
  762. requestWhois(packet.destination());
  763. }
  764. return false;
  765. }
  766. } // namespace ZeroTier