Switch.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2012-2013 ZeroTier Networks LLC
  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 <stdio.h>
  28. #include <stdlib.h>
  29. #include <algorithm>
  30. #include <utility>
  31. #include <stdexcept>
  32. #include "Switch.hpp"
  33. #include "Node.hpp"
  34. #include "EthernetTap.hpp"
  35. #include "InetAddress.hpp"
  36. #include "Topology.hpp"
  37. #include "RuntimeEnvironment.hpp"
  38. #include "Defaults.hpp"
  39. #include "Peer.hpp"
  40. #include "NodeConfig.hpp"
  41. #include "Demarc.hpp"
  42. #include "Filter.hpp"
  43. #include "../version.h"
  44. namespace ZeroTier {
  45. Switch::Switch(const RuntimeEnvironment *renv) :
  46. _r(renv)
  47. {
  48. }
  49. Switch::~Switch()
  50. {
  51. }
  52. void Switch::onRemotePacket(Demarc::Port localPort,const InetAddress &fromAddr,const Buffer<4096> &data)
  53. {
  54. try {
  55. if (data.size() > ZT_PROTO_MIN_FRAGMENT_LENGTH) {
  56. if (data[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] == ZT_PACKET_FRAGMENT_INDICATOR)
  57. _handleRemotePacketFragment(localPort,fromAddr,data);
  58. else if (data.size() > ZT_PROTO_MIN_PACKET_LENGTH)
  59. _handleRemotePacketHead(localPort,fromAddr,data);
  60. else {
  61. TRACE("dropped runt packet from %s",fromAddr.toString().c_str());
  62. }
  63. }
  64. } catch (std::exception &ex) {
  65. TRACE("dropped packet from %s: %s",fromAddr.toString().c_str(),ex.what());
  66. } catch ( ... ) {
  67. TRACE("dropped packet from %s: unknown exception",fromAddr.toString().c_str());
  68. }
  69. }
  70. void Switch::onLocalEthernet(const SharedPtr<Network> &network,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data)
  71. {
  72. if (from != network->tap().mac()) {
  73. LOG("ignored tap: %s -> %s %s (bridging is not (yet?) supported)",from.toString().c_str(),to.toString().c_str(),Filter::etherTypeName(etherType));
  74. return;
  75. }
  76. if (to == network->tap().mac()) {
  77. // Right thing to do? Will this ever happen?
  78. TRACE("weird OS behavior: ethernet frame received from self, reflecting");
  79. network->tap().put(from,to,etherType,data.data(),data.size());
  80. return;
  81. }
  82. if ((etherType != ZT_ETHERTYPE_ARP)&&(etherType != ZT_ETHERTYPE_IPV4)&&(etherType != ZT_ETHERTYPE_IPV6)) {
  83. LOG("ignored tap: %s -> %s %s (not a supported etherType)",from.toString().c_str(),to.toString().c_str(),Filter::etherTypeName(etherType));
  84. return;
  85. }
  86. if (to.isMulticast()) {
  87. MulticastGroup mg(to,0);
  88. if (to.isBroadcast()) {
  89. // Cram IPv4 IP into ADI field to make IPv4 ARP broadcast channel specific and scalable
  90. if ((etherType == ZT_ETHERTYPE_ARP)&&(data.size() == 28)&&(data[2] == 0x08)&&(data[3] == 0x00)&&(data[4] == 6)&&(data[5] == 4)&&(data[7] == 0x01))
  91. mg = MulticastGroup::deriveMulticastGroupForAddressResolution(InetAddress(data.field(24,4),4,0));
  92. }
  93. Multicaster::MulticastBloomFilter newbf;
  94. SharedPtr<Peer> propPeers[ZT_MULTICAST_PROPAGATION_BREADTH];
  95. unsigned int np = _multicaster.pickNextPropagationPeers(
  96. *(_r->topology),
  97. network->id(),
  98. mg,
  99. _r->identity.address(),
  100. Address(),
  101. newbf,
  102. ZT_MULTICAST_PROPAGATION_BREADTH,
  103. propPeers,
  104. Utils::now());
  105. if (!np)
  106. return;
  107. std::string signature(Multicaster::signMulticastPacket(_r->identity,network->id(),from,mg,etherType,data.data(),data.size()));
  108. if (!signature.length()) {
  109. TRACE("failure signing multicast message!");
  110. return;
  111. }
  112. Packet outpTmpl(propPeers[0]->address(),_r->identity.address(),Packet::VERB_MULTICAST_FRAME);
  113. outpTmpl.append((uint8_t)0);
  114. outpTmpl.append((uint64_t)network->id());
  115. outpTmpl.append(_r->identity.address().data(),ZT_ADDRESS_LENGTH);
  116. outpTmpl.append(from.data,6);
  117. outpTmpl.append(mg.mac().data,6);
  118. outpTmpl.append((uint32_t)mg.adi());
  119. outpTmpl.append(newbf.data(),ZT_PROTO_VERB_MULTICAST_FRAME_BLOOM_FILTER_SIZE_BYTES);
  120. outpTmpl.append((uint8_t)0); // 0 hops
  121. outpTmpl.append((uint16_t)etherType);
  122. outpTmpl.append((uint16_t)data.size());
  123. outpTmpl.append((uint16_t)signature.length());
  124. outpTmpl.append(data.data(),data.size());
  125. outpTmpl.append(signature.data(),signature.length());
  126. outpTmpl.compress();
  127. send(outpTmpl,true);
  128. for(unsigned int i=1;i<np;++i) {
  129. outpTmpl.newInitializationVector();
  130. outpTmpl.setDestination(propPeers[i]->address());
  131. send(outpTmpl,true);
  132. }
  133. } else if (to.isZeroTier()) {
  134. // Simple unicast frame from us to another node
  135. Address toZT(to.data + 1);
  136. if (network->isAllowed(toZT)) {
  137. Packet outp(toZT,_r->identity.address(),Packet::VERB_FRAME);
  138. outp.append(network->id());
  139. outp.append((uint16_t)etherType);
  140. outp.append(data);
  141. outp.compress();
  142. send(outp,true);
  143. } else {
  144. TRACE("UNICAST: %s -> %s %s (dropped, destination not a member of closed network %llu)",from.toString().c_str(),to.toString().c_str(),Filter::etherTypeName(etherType),network->id());
  145. }
  146. } else {
  147. TRACE("UNICAST: %s -> %s %s (dropped, destination MAC not ZeroTier)",from.toString().c_str(),to.toString().c_str(),Filter::etherTypeName(etherType));
  148. }
  149. }
  150. void Switch::send(const Packet &packet,bool encrypt)
  151. {
  152. //TRACE("%.16llx %s -> %s (size: %u) (enc: %s)",packet.packetId(),Packet::verbString(packet.verb()),packet.destination().toString().c_str(),packet.size(),(encrypt ? "yes" : "no"));
  153. if (!_trySend(packet,encrypt)) {
  154. Mutex::Lock _l(_txQueue_m);
  155. _txQueue.insert(std::pair< Address,TXQueueEntry >(packet.destination(),TXQueueEntry(Utils::now(),packet,encrypt)));
  156. }
  157. }
  158. void Switch::sendHELLO(const Address &dest)
  159. {
  160. Packet outp(dest,_r->identity.address(),Packet::VERB_HELLO);
  161. outp.append((unsigned char)ZT_PROTO_VERSION);
  162. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  163. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  164. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  165. outp.append(Utils::now());
  166. _r->identity.serialize(outp,false);
  167. send(outp,false);
  168. }
  169. bool Switch::sendHELLO(const SharedPtr<Peer> &dest,Demarc::Port localPort,const InetAddress &addr)
  170. {
  171. Packet outp(dest->address(),_r->identity.address(),Packet::VERB_HELLO);
  172. outp.append((unsigned char)ZT_PROTO_VERSION);
  173. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  174. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  175. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  176. outp.append(Utils::now());
  177. _r->identity.serialize(outp,false);
  178. outp.hmacSet(dest->macKey());
  179. return _r->demarc->send(localPort,addr,outp.data(),outp.size(),-1);
  180. }
  181. bool Switch::unite(const Address &p1,const Address &p2,bool force)
  182. {
  183. SharedPtr<Peer> p1p = _r->topology->getPeer(p1);
  184. if (!p1p)
  185. return false;
  186. SharedPtr<Peer> p2p = _r->topology->getPeer(p2);
  187. if (!p2p)
  188. return false;
  189. uint64_t now = Utils::now();
  190. std::pair<InetAddress,InetAddress> cg(Peer::findCommonGround(*p1p,*p2p,now));
  191. if (!(cg.first))
  192. return false;
  193. // Addresses are sorted in key for last unite attempt map for order
  194. // invariant lookup: (p1,p2) == (p2,p1)
  195. Array<Address,2> uniteKey;
  196. if (p1 >= p2) {
  197. uniteKey[0] = p2;
  198. uniteKey[1] = p1;
  199. } else {
  200. uniteKey[0] = p1;
  201. uniteKey[1] = p2;
  202. }
  203. {
  204. Mutex::Lock _l(_lastUniteAttempt_m);
  205. std::map< Array< Address,2 >,uint64_t >::const_iterator e(_lastUniteAttempt.find(uniteKey));
  206. if ((!force)&&(e != _lastUniteAttempt.end())&&((now - e->second) < ZT_MIN_UNITE_INTERVAL))
  207. return false;
  208. else _lastUniteAttempt[uniteKey] = now;
  209. }
  210. TRACE("unite: %s(%s) <> %s(%s)",p1.toString().c_str(),cg.second.toString().c_str(),p2.toString().c_str(),cg.first.toString().c_str());
  211. { // tell p1 where to find p2
  212. Packet outp(p1,_r->identity.address(),Packet::VERB_RENDEZVOUS);
  213. outp.append(p2.data(),ZT_ADDRESS_LENGTH);
  214. outp.append((uint16_t)cg.first.port());
  215. if (cg.first.isV6()) {
  216. outp.append((unsigned char)16);
  217. outp.append(cg.first.rawIpData(),16);
  218. } else {
  219. outp.append((unsigned char)4);
  220. outp.append(cg.first.rawIpData(),4);
  221. }
  222. outp.encrypt(p1p->cryptKey());
  223. outp.hmacSet(p1p->macKey());
  224. p1p->send(_r,outp.data(),outp.size(),false,Packet::VERB_RENDEZVOUS,now);
  225. }
  226. { // tell p2 where to find p1
  227. Packet outp(p2,_r->identity.address(),Packet::VERB_RENDEZVOUS);
  228. outp.append(p1.data(),ZT_ADDRESS_LENGTH);
  229. outp.append((uint16_t)cg.second.port());
  230. if (cg.second.isV6()) {
  231. outp.append((unsigned char)16);
  232. outp.append(cg.second.rawIpData(),16);
  233. } else {
  234. outp.append((unsigned char)4);
  235. outp.append(cg.second.rawIpData(),4);
  236. }
  237. outp.encrypt(p2p->cryptKey());
  238. outp.hmacSet(p2p->macKey());
  239. p2p->send(_r,outp.data(),outp.size(),false,Packet::VERB_RENDEZVOUS,now);
  240. }
  241. return true;
  242. }
  243. unsigned long Switch::doTimerTasks()
  244. {
  245. unsigned long nextDelay = ~((unsigned long)0); // big number, caller will cap return value
  246. uint64_t now = Utils::now();
  247. {
  248. Mutex::Lock _l(_rendezvousQueue_m);
  249. for(std::map< Address,RendezvousQueueEntry >::iterator i(_rendezvousQueue.begin());i!=_rendezvousQueue.end();) {
  250. if (now >= i->second.fireAtTime) {
  251. SharedPtr<Peer> withPeer = _r->topology->getPeer(i->first);
  252. if (withPeer) {
  253. TRACE("sending NAT-T HELLO to %s(%s)",i->first.toString().c_str(),i->second.inaddr.toString().c_str());
  254. sendHELLO(withPeer,i->second.localPort,i->second.inaddr);
  255. }
  256. _rendezvousQueue.erase(i++);
  257. } else {
  258. nextDelay = std::min(nextDelay,(unsigned long)(i->second.fireAtTime - now));
  259. ++i;
  260. }
  261. }
  262. }
  263. {
  264. Mutex::Lock _l(_outstandingWhoisRequests_m);
  265. for(std::map< Address,WhoisRequest >::iterator i(_outstandingWhoisRequests.begin());i!=_outstandingWhoisRequests.end();) {
  266. unsigned long since = (unsigned long)(now - i->second.lastSent);
  267. if (since >= ZT_WHOIS_RETRY_DELAY) {
  268. if (i->second.retries >= ZT_MAX_WHOIS_RETRIES) {
  269. TRACE("WHOIS %s timed out",i->first.toString().c_str());
  270. _outstandingWhoisRequests.erase(i++);
  271. continue;
  272. } else {
  273. i->second.lastSent = now;
  274. i->second.peersConsulted[i->second.retries] = _sendWhoisRequest(i->first,i->second.peersConsulted,i->second.retries);
  275. ++i->second.retries;
  276. TRACE("WHOIS %s (retry %u)",i->first.toString().c_str(),i->second.retries);
  277. nextDelay = std::min(nextDelay,(unsigned long)ZT_WHOIS_RETRY_DELAY);
  278. }
  279. } else nextDelay = std::min(nextDelay,ZT_WHOIS_RETRY_DELAY - since);
  280. ++i;
  281. }
  282. }
  283. {
  284. Mutex::Lock _l(_txQueue_m);
  285. for(std::multimap< Address,TXQueueEntry >::iterator i(_txQueue.begin());i!=_txQueue.end();) {
  286. if (_trySend(i->second.packet,i->second.encrypt))
  287. _txQueue.erase(i++);
  288. else if ((now - i->second.creationTime) > ZT_TRANSMIT_QUEUE_TIMEOUT) {
  289. TRACE("TX %s -> %s timed out",i->second.packet.source().toString().c_str(),i->second.packet.destination().toString().c_str());
  290. _txQueue.erase(i++);
  291. } else ++i;
  292. }
  293. }
  294. {
  295. Mutex::Lock _l(_rxQueue_m);
  296. for(std::multimap< Address,SharedPtr<PacketDecoder> >::iterator i(_rxQueue.begin());i!=_rxQueue.end();) {
  297. if ((now - i->second->receiveTime()) > ZT_RECEIVE_QUEUE_TIMEOUT) {
  298. TRACE("RX %s -> %s timed out",i->second->source().toString().c_str(),i->second->destination().toString().c_str());
  299. _rxQueue.erase(i++);
  300. } else ++i;
  301. }
  302. }
  303. {
  304. Mutex::Lock _l(_defragQueue_m);
  305. for(std::map< uint64_t,DefragQueueEntry >::iterator i(_defragQueue.begin());i!=_defragQueue.end();) {
  306. if ((now - i->second.creationTime) > ZT_FRAGMENTED_PACKET_RECEIVE_TIMEOUT) {
  307. TRACE("incomplete fragmented packet %.16llx timed out, fragments discarded",i->first);
  308. _defragQueue.erase(i++);
  309. } else ++i;
  310. }
  311. }
  312. return std::max(nextDelay,(unsigned long)10); // minimum delay
  313. }
  314. void Switch::announceMulticastGroups(const std::map< SharedPtr<Network>,std::set<MulticastGroup> > &allMemberships)
  315. {
  316. std::vector< SharedPtr<Peer> > directPeers;
  317. _r->topology->eachPeer(Topology::CollectPeersWithActiveDirectPath(directPeers));
  318. #ifdef ZT_TRACE
  319. unsigned int totalMulticastGroups = 0;
  320. for(std::map< SharedPtr<Network>,std::set<MulticastGroup> >::const_iterator i(allMemberships.begin());i!=allMemberships.end();++i)
  321. totalMulticastGroups += (unsigned int)i->second.size();
  322. TRACE("announcing %u multicast groups for %u networks to %u peers",totalMulticastGroups,(unsigned int)allMemberships.size(),(unsigned int)directPeers.size());
  323. #endif
  324. for(std::vector< SharedPtr<Peer> >::iterator p(directPeers.begin());p!=directPeers.end();++p) {
  325. Packet outp((*p)->address(),_r->identity.address(),Packet::VERB_MULTICAST_LIKE);
  326. for(std::map< SharedPtr<Network>,std::set<MulticastGroup> >::const_iterator nwmgs(allMemberships.begin());nwmgs!=allMemberships.end();++nwmgs) {
  327. if ((nwmgs->first->open())||(_r->topology->isSupernode((*p)->address()))||(nwmgs->first->isMember((*p)->address()))) {
  328. for(std::set<MulticastGroup>::iterator mg(nwmgs->second.begin());mg!=nwmgs->second.end();++mg) {
  329. if ((outp.size() + 18) > ZT_UDP_DEFAULT_PAYLOAD_MTU) {
  330. send(outp,true);
  331. outp.reset((*p)->address(),_r->identity.address(),Packet::VERB_MULTICAST_LIKE);
  332. }
  333. outp.append((uint64_t)nwmgs->first->id());
  334. outp.append(mg->mac().data,6);
  335. outp.append((uint32_t)mg->adi());
  336. }
  337. }
  338. }
  339. if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH)
  340. send(outp,true);
  341. }
  342. }
  343. void Switch::requestWhois(const Address &addr)
  344. {
  345. TRACE("requesting WHOIS for %s",addr.toString().c_str());
  346. {
  347. Mutex::Lock _l(_outstandingWhoisRequests_m);
  348. std::pair< std::map< Address,WhoisRequest >::iterator,bool > entry(_outstandingWhoisRequests.insert(std::pair<Address,WhoisRequest>(addr,WhoisRequest())));
  349. entry.first->second.lastSent = Utils::now();
  350. entry.first->second.retries = 0; // reset retry count if entry already existed
  351. }
  352. _sendWhoisRequest(addr,(const Address *)0,0);
  353. }
  354. void Switch::_CBaddPeerFromHello(void *arg,const SharedPtr<Peer> &p,Topology::PeerVerifyResult result)
  355. {
  356. _CBaddPeerFromHello_Data *req = (_CBaddPeerFromHello_Data *)arg;
  357. const RuntimeEnvironment *_r = req->parent->_r;
  358. switch(result) {
  359. case Topology::PEER_VERIFY_ACCEPTED_NEW:
  360. case Topology::PEER_VERIFY_ACCEPTED_ALREADY_HAVE:
  361. case Topology::PEER_VERIFY_ACCEPTED_DISPLACED_INVALID_ADDRESS: {
  362. req->parent->_finishWhoisRequest(p);
  363. Packet outp(req->source,_r->identity.address(),Packet::VERB_OK);
  364. outp.append((unsigned char)Packet::VERB_HELLO);
  365. outp.append(req->helloPacketId);
  366. outp.append(req->helloTimestamp);
  367. outp.encrypt(p->cryptKey());
  368. outp.hmacSet(p->macKey());
  369. req->parent->_r->demarc->send(req->localPort,req->fromAddr,outp.data(),outp.size(),-1);
  370. } break;
  371. case Topology::PEER_VERIFY_REJECTED_INVALID_IDENTITY: {
  372. Packet outp(req->source,_r->identity.address(),Packet::VERB_ERROR);
  373. outp.append((unsigned char)Packet::VERB_HELLO);
  374. outp.append(req->helloPacketId);
  375. outp.append((unsigned char)Packet::ERROR_IDENTITY_INVALID);
  376. outp.encrypt(p->cryptKey());
  377. outp.hmacSet(p->macKey());
  378. req->parent->_r->demarc->send(req->localPort,req->fromAddr,outp.data(),outp.size(),-1);
  379. } break;
  380. case Topology::PEER_VERIFY_REJECTED_DUPLICATE:
  381. case Topology::PEER_VERIFY_REJECTED_DUPLICATE_TRIAGED: {
  382. Packet outp(req->source,_r->identity.address(),Packet::VERB_ERROR);
  383. outp.append((unsigned char)Packet::VERB_HELLO);
  384. outp.append(req->helloPacketId);
  385. outp.append((unsigned char)Packet::ERROR_IDENTITY_COLLISION);
  386. outp.encrypt(p->cryptKey());
  387. outp.hmacSet(p->macKey());
  388. req->parent->_r->demarc->send(req->localPort,req->fromAddr,outp.data(),outp.size(),-1);
  389. } break;
  390. }
  391. delete req;
  392. }
  393. void Switch::_CBaddPeerFromWhois(void *arg,const SharedPtr<Peer> &p,Topology::PeerVerifyResult result)
  394. {
  395. switch(result) {
  396. case Topology::PEER_VERIFY_ACCEPTED_NEW:
  397. case Topology::PEER_VERIFY_ACCEPTED_ALREADY_HAVE:
  398. case Topology::PEER_VERIFY_ACCEPTED_DISPLACED_INVALID_ADDRESS:
  399. ((Switch *)arg)->_finishWhoisRequest(p);
  400. break;
  401. default:
  402. break;
  403. }
  404. }
  405. void Switch::_finishWhoisRequest(const SharedPtr<Peer> &peer)
  406. {
  407. {
  408. Mutex::Lock _l(_outstandingWhoisRequests_m);
  409. _outstandingWhoisRequests.erase(peer->address());
  410. }
  411. {
  412. Mutex::Lock _l(_rxQueue_m);
  413. std::pair< std::multimap< Address,SharedPtr<PacketDecoder> >::iterator,std::multimap< Address,SharedPtr<PacketDecoder> >::iterator > waitingRxQueueItems(_rxQueue.equal_range(peer->address()));
  414. for(std::multimap< Address,SharedPtr<PacketDecoder> >::iterator rxi(waitingRxQueueItems.first);rxi!=waitingRxQueueItems.second;) {
  415. if (rxi->second->tryDecode(_r))
  416. _rxQueue.erase(rxi++);
  417. else ++rxi;
  418. }
  419. }
  420. {
  421. Mutex::Lock _l(_txQueue_m);
  422. std::pair< std::multimap< Address,TXQueueEntry >::iterator,std::multimap< Address,TXQueueEntry >::iterator > waitingTxQueueItems(_txQueue.equal_range(peer->address()));
  423. for(std::multimap< Address,TXQueueEntry >::iterator txi(waitingTxQueueItems.first);txi!=waitingTxQueueItems.second;) {
  424. if (_trySend(txi->second.packet,txi->second.encrypt))
  425. _txQueue.erase(txi++);
  426. else ++txi;
  427. }
  428. }
  429. }
  430. void Switch::_handleRemotePacketFragment(Demarc::Port localPort,const InetAddress &fromAddr,const Buffer<4096> &data)
  431. {
  432. Packet::Fragment fragment(data);
  433. Address destination(fragment.destination());
  434. if (destination != _r->identity.address()) {
  435. // Fragment is not for us, so try to relay it
  436. if (fragment.hops() < ZT_RELAY_MAX_HOPS) {
  437. fragment.incrementHops();
  438. SharedPtr<Peer> relayTo = _r->topology->getPeer(destination);
  439. if ((!relayTo)||(!relayTo->send(_r,fragment.data(),fragment.size(),true,Packet::VERB_NOP,Utils::now()))) {
  440. relayTo = _r->topology->getBestSupernode();
  441. if (relayTo)
  442. relayTo->send(_r,fragment.data(),fragment.size(),true,Packet::VERB_NOP,Utils::now());
  443. }
  444. } else {
  445. TRACE("dropped relay [fragment](%s) -> %s, max hops exceeded",fromAddr.toString().c_str(),destination.toString().c_str());
  446. }
  447. } else {
  448. // Fragment looks like ours
  449. uint64_t pid = fragment.packetId();
  450. unsigned int fno = fragment.fragmentNumber();
  451. unsigned int tf = fragment.totalFragments();
  452. if ((tf <= ZT_MAX_PACKET_FRAGMENTS)&&(fno < ZT_MAX_PACKET_FRAGMENTS)&&(fno > 0)&&(tf > 1)) {
  453. // Fragment appears basically sane. Its fragment number must be
  454. // 1 or more, since a Packet with fragmented bit set is fragment 0.
  455. // Total fragments must be more than 1, otherwise why are we
  456. // seeing a Packet::Fragment?
  457. Mutex::Lock _l(_defragQueue_m);
  458. std::map< uint64_t,DefragQueueEntry >::iterator dqe(_defragQueue.find(pid));
  459. if (dqe == _defragQueue.end()) {
  460. // We received a Packet::Fragment without its head, so queue it and wait
  461. DefragQueueEntry &dq = _defragQueue[pid];
  462. dq.creationTime = Utils::now();
  463. dq.frags[fno - 1] = fragment;
  464. dq.totalFragments = tf; // total fragment count is known
  465. dq.haveFragments = 1 << fno; // we have only this fragment
  466. //TRACE("fragment (%u/%u) of %.16llx from %s",fno + 1,tf,pid,fromAddr.toString().c_str());
  467. } else if (!(dqe->second.haveFragments & (1 << fno))) {
  468. // We have other fragments and maybe the head, so add this one and check
  469. dqe->second.frags[fno - 1] = fragment;
  470. dqe->second.totalFragments = tf;
  471. //TRACE("fragment (%u/%u) of %.16llx from %s",fno + 1,tf,pid,fromAddr.toString().c_str());
  472. if (Utils::countBits(dqe->second.haveFragments |= (1 << fno)) == tf) {
  473. // We have all fragments -- assemble and process full Packet
  474. //TRACE("packet %.16llx is complete, assembling and processing...",pid);
  475. SharedPtr<PacketDecoder> packet(dqe->second.frag0);
  476. for(unsigned int f=1;f<tf;++f)
  477. packet->append(dqe->second.frags[f - 1].payload(),dqe->second.frags[f - 1].payloadLength());
  478. _defragQueue.erase(dqe);
  479. if (!packet->tryDecode(_r)) {
  480. Mutex::Lock _l(_rxQueue_m);
  481. _rxQueue.insert(std::pair< Address,SharedPtr<PacketDecoder> >(destination,packet));
  482. }
  483. }
  484. } // else this is a duplicate fragment, ignore
  485. }
  486. }
  487. }
  488. void Switch::_handleRemotePacketHead(Demarc::Port localPort,const InetAddress &fromAddr,const Buffer<4096> &data)
  489. {
  490. SharedPtr<PacketDecoder> packet(new PacketDecoder(data,localPort,fromAddr));
  491. Address destination(packet->destination());
  492. if (destination != _r->identity.address()) {
  493. // Packet is not for us, so try to relay it
  494. if (packet->hops() < ZT_RELAY_MAX_HOPS) {
  495. packet->incrementHops();
  496. SharedPtr<Peer> relayTo = _r->topology->getPeer(destination);
  497. if ((relayTo)&&(relayTo->send(_r,packet->data(),packet->size(),true,Packet::VERB_NOP,Utils::now()))) {
  498. unite(packet->source(),destination,false); // periodically try to get them to talk directly
  499. } else {
  500. relayTo = _r->topology->getBestSupernode();
  501. if (relayTo)
  502. relayTo->send(_r,packet->data(),packet->size(),true,Packet::VERB_NOP,Utils::now());
  503. }
  504. } else {
  505. TRACE("dropped relay %s(%s) -> %s, max hops exceeded",packet->source().toString().c_str(),fromAddr.toString().c_str(),destination.toString().c_str());
  506. }
  507. } else if (packet->fragmented()) {
  508. // Packet is the head of a fragmented packet series
  509. uint64_t pid = packet->packetId();
  510. Mutex::Lock _l(_defragQueue_m);
  511. std::map< uint64_t,DefragQueueEntry >::iterator dqe(_defragQueue.find(pid));
  512. if (dqe == _defragQueue.end()) {
  513. // If we have no other fragments yet, create an entry and save the head
  514. DefragQueueEntry &dq = _defragQueue[pid];
  515. dq.creationTime = Utils::now();
  516. dq.frag0 = packet;
  517. dq.totalFragments = 0; // 0 == unknown, waiting for Packet::Fragment
  518. dq.haveFragments = 1; // head is first bit (left to right)
  519. //TRACE("fragment (0/?) of %.16llx from %s",pid,fromAddr.toString().c_str());
  520. } else if (!(dqe->second.haveFragments & 1)) {
  521. // If we have other fragments but no head, see if we are complete with the head
  522. if ((dqe->second.totalFragments)&&(Utils::countBits(dqe->second.haveFragments |= 1) == dqe->second.totalFragments)) {
  523. // We have all fragments -- assemble and process full Packet
  524. //TRACE("packet %.16llx is complete, assembling and processing...",pid);
  525. // packet already contains head, so append fragments
  526. for(unsigned int f=1;f<dqe->second.totalFragments;++f)
  527. packet->append(dqe->second.frags[f - 1].payload(),dqe->second.frags[f - 1].payloadLength());
  528. _defragQueue.erase(dqe);
  529. if (!packet->tryDecode(_r)) {
  530. Mutex::Lock _l(_rxQueue_m);
  531. _rxQueue.insert(std::pair< Address,SharedPtr<PacketDecoder> >(destination,packet));
  532. }
  533. } else {
  534. // Still waiting on more fragments, so queue the head
  535. dqe->second.frag0 = packet;
  536. }
  537. } // else this is a duplicate head, ignore
  538. } else {
  539. // Packet is unfragmented, so just process it
  540. if (!packet->tryDecode(_r)) {
  541. Mutex::Lock _l(_rxQueue_m);
  542. _rxQueue.insert(std::pair< Address,SharedPtr<PacketDecoder> >(destination,packet));
  543. }
  544. }
  545. }
  546. Address Switch::_sendWhoisRequest(const Address &addr,const Address *peersAlreadyConsulted,unsigned int numPeersAlreadyConsulted)
  547. {
  548. SharedPtr<Peer> supernode(_r->topology->getBestSupernode(peersAlreadyConsulted,numPeersAlreadyConsulted));
  549. if (supernode) {
  550. Packet outp(supernode->address(),_r->identity.address(),Packet::VERB_WHOIS);
  551. outp.append(addr.data(),ZT_ADDRESS_LENGTH);
  552. outp.encrypt(supernode->cryptKey());
  553. outp.hmacSet(supernode->macKey());
  554. supernode->send(_r,outp.data(),outp.size(),false,Packet::VERB_WHOIS,Utils::now());
  555. return supernode->address();
  556. }
  557. return Address();
  558. }
  559. bool Switch::_trySend(const Packet &packet,bool encrypt)
  560. {
  561. SharedPtr<Peer> peer(_r->topology->getPeer(packet.destination()));
  562. if (peer) {
  563. uint64_t now = Utils::now();
  564. bool isRelay;
  565. SharedPtr<Peer> via;
  566. if ((_r->topology->isSupernode(peer->address()))||(peer->hasActiveDirectPath(now))) {
  567. isRelay = false;
  568. via = peer;
  569. } else {
  570. isRelay = true;
  571. via = _r->topology->getBestSupernode();
  572. if (!via)
  573. return false;
  574. }
  575. Packet tmp(packet);
  576. unsigned int chunkSize = std::min(tmp.size(),(unsigned int)ZT_UDP_DEFAULT_PAYLOAD_MTU);
  577. tmp.setFragmented(chunkSize < tmp.size());
  578. if (encrypt)
  579. tmp.encrypt(peer->cryptKey());
  580. tmp.hmacSet(peer->macKey());
  581. Packet::Verb verb = packet.verb();
  582. if (via->send(_r,tmp.data(),chunkSize,isRelay,verb,now)) {
  583. if (chunkSize < tmp.size()) {
  584. // Too big for one bite, fragment the rest
  585. unsigned int fragStart = chunkSize;
  586. unsigned int remaining = tmp.size() - chunkSize;
  587. unsigned int fragsRemaining = (remaining / (ZT_UDP_DEFAULT_PAYLOAD_MTU - ZT_PROTO_MIN_FRAGMENT_LENGTH));
  588. if ((fragsRemaining * (ZT_UDP_DEFAULT_PAYLOAD_MTU - ZT_PROTO_MIN_FRAGMENT_LENGTH)) < remaining)
  589. ++fragsRemaining;
  590. unsigned int totalFragments = fragsRemaining + 1;
  591. for(unsigned int f=0;f<fragsRemaining;++f) {
  592. chunkSize = std::min(remaining,(unsigned int)(ZT_UDP_DEFAULT_PAYLOAD_MTU - ZT_PROTO_MIN_FRAGMENT_LENGTH));
  593. Packet::Fragment frag(tmp,fragStart,chunkSize,f + 1,totalFragments);
  594. if (!via->send(_r,frag.data(),frag.size(),isRelay,verb,now)) {
  595. TRACE("WARNING: packet send to %s failed on later fragment #%u (check IP layer buffer sizes?)",via->address().toString().c_str(),f + 1);
  596. return false;
  597. }
  598. fragStart += chunkSize;
  599. remaining -= chunkSize;
  600. }
  601. }
  602. return true;
  603. }
  604. return false;
  605. }
  606. requestWhois(packet.destination());
  607. return false;
  608. }
  609. } // namespace ZeroTier