Switch.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057
  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. Packet packet;
  55. try {
  56. if (data.size() > ZT_PROTO_MIN_FRAGMENT_LENGTH) {
  57. if (data[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] == ZT_PACKET_FRAGMENT_INDICATOR) {
  58. _handleRemotePacketFragment(localPort,fromAddr,data);
  59. } else if (data.size() > ZT_PROTO_MIN_PACKET_LENGTH) {
  60. _handleRemotePacketHead(localPort,fromAddr,data);
  61. }
  62. }
  63. } catch (std::exception &ex) {
  64. TRACE("dropped packet from %s: %s",fromAddr.toString().c_str(),ex.what());
  65. } catch ( ... ) {
  66. TRACE("dropped packet from %s: unknown exception",fromAddr.toString().c_str());
  67. }
  68. }
  69. void Switch::onLocalEthernet(const SharedPtr<Network> &network,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data)
  70. {
  71. if (from != network->tap().mac()) {
  72. LOG("ignored tap: %s -> %s %s (bridging is not (yet?) supported)",from.toString().c_str(),to.toString().c_str(),Filter::etherTypeName(etherType));
  73. return;
  74. }
  75. if (to == network->tap().mac()) {
  76. // Right thing to do? Will this ever happen?
  77. TRACE("weird OS behavior: ethernet frame received from self, reflecting");
  78. network->tap().put(from,to,etherType,data.data(),data.size());
  79. return;
  80. }
  81. if ((etherType != ZT_ETHERTYPE_ARP)&&(etherType != ZT_ETHERTYPE_IPV4)&&(etherType != ZT_ETHERTYPE_IPV6)) {
  82. LOG("ignored tap: %s -> %s %s (not a supported etherType)",from.toString().c_str(),to.toString().c_str(),Filter::etherTypeName(etherType));
  83. return;
  84. }
  85. if (to.isMulticast()) {
  86. MulticastGroup mg(to,0);
  87. if (to.isBroadcast()) {
  88. // Cram IPv4 IP into ADI field to make IPv4 ARP broadcast channel specific and scalable
  89. if ((etherType == ZT_ETHERTYPE_ARP)&&(data.size() == 28)&&(data[2] == 0x08)&&(data[3] == 0x00)&&(data[4] == 6)&&(data[5] == 4)&&(data[7] == 0x01))
  90. mg = MulticastGroup::deriveMulticastGroupForAddressResolution(InetAddress(data.field(24,4),4,0));
  91. }
  92. Multicaster::MulticastBloomFilter newbf;
  93. SharedPtr<Peer> propPeers[ZT_MULTICAST_PROPAGATION_BREADTH];
  94. unsigned int np = _multicaster.pickNextPropagationPeers(
  95. *(_r->topology),
  96. network->id(),
  97. mg,
  98. _r->identity.address(),
  99. Address(),
  100. newbf,
  101. ZT_MULTICAST_PROPAGATION_BREADTH,
  102. propPeers,
  103. Utils::now());
  104. if (!np)
  105. return;
  106. std::string signature(Multicaster::signMulticastPacket(_r->identity,network->id(),from,mg,etherType,data,len));
  107. if (!signature.length()) {
  108. TRACE("failure signing multicast message!");
  109. return;
  110. }
  111. Packet outpTmpl(propPeers[0]->address(),_r->identity.address(),Packet::VERB_MULTICAST_FRAME);
  112. outpTmpl.append((uint8_t)0);
  113. outpTmpl.append((uint64_t)network->id());
  114. outpTmpl.append(_r->identity.address().data(),ZT_ADDRESS_LENGTH);
  115. outpTmpl.append(from.data,6);
  116. outpTmpl.append(mg.mac().data,6);
  117. outpTmpl.append((uint32_t)mg.adi());
  118. outpTmpl.append(newBloom.data(),ZT_PROTO_VERB_MULTICAST_FRAME_BLOOM_FILTER_SIZE);
  119. outpTmpl.append((uint8_t)0); // 0 hops
  120. outpTmpl.append((uint16_t)etherType);
  121. outpTmpl.append((uint16_t)len);
  122. outpTmpl.append((uint16_t)signature.length());
  123. outpTmpl.append(data,len);
  124. outpTmpl.append(signature.data(),signature.length());
  125. outpTmpl.compress();
  126. send(outpTmpl,true);
  127. for(unsigned int i=1;i<np;++i) {
  128. outpTmpl.newInitializationVector();
  129. outpTmpl.setDestination(propPeers[i]->address());
  130. send(outpTmpl,true);
  131. }
  132. } else if (to.isZeroTier()) {
  133. // Simple unicast frame from us to another node
  134. Address toZT(to.data + 1);
  135. if (network->isAllowed(toZT)) {
  136. Packet outp(toZT,_r->identity.address(),Packet::VERB_FRAME);
  137. outp.append(network->id());
  138. outp.append((uint16_t)etherType);
  139. outp.append(data);
  140. outp.compress();
  141. send(outp,true);
  142. } else {
  143. 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());
  144. }
  145. } else {
  146. TRACE("UNICAST: %s -> %s %s (dropped, destination MAC not ZeroTier)",from.toString().c_str(),to.toString().c_str(),Filter::etherTypeName(etherType));
  147. }
  148. }
  149. void Switch::send(const Packet &packet,bool encrypt)
  150. {
  151. //TRACE("%.16llx %s -> %s (size: %u) (enc: %s)",packet.packetId(),Packet::verbString(packet.verb()),packet.destination().toString().c_str(),packet.size(),(encrypt ? "yes" : "no"));
  152. if (!_trySend(packet,encrypt)) {
  153. Mutex::Lock _l(_txQueue_m);
  154. _txQueue.insert(std::pair< uint64_t,TXQueueEntry >(packet.packetId(),TXQueueEntry(Utils::now(),packet,encrypt)));
  155. }
  156. }
  157. void Switch::sendHELLO(const Address &dest)
  158. {
  159. Packet outp(dest,_r->identity.address(),Packet::VERB_HELLO);
  160. outp.append((unsigned char)ZT_PROTO_VERSION);
  161. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  162. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  163. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  164. outp.append(Utils::now());
  165. _r->identity.serialize(outp,false);
  166. send(outp,false);
  167. }
  168. bool Switch::sendHELLO(const SharedPtr<Peer> &dest,Demarc::Port localPort,const InetAddress &addr)
  169. {
  170. Packet outp(dest->address(),_r->identity.address(),Packet::VERB_HELLO);
  171. outp.append((unsigned char)ZT_PROTO_VERSION);
  172. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  173. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  174. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  175. outp.append(Utils::now());
  176. _r->identity.serialize(outp,false);
  177. outp.hmacSet(dest->macKey());
  178. return _r->demarc->send(localPort,addr,outp.data(),outp.size(),-1);
  179. }
  180. bool Switch::unite(const Address &p1,const Address &p2,bool force)
  181. {
  182. SharedPtr<Peer> p1p = _r->topology->getPeer(p1);
  183. if (!p1p)
  184. return false;
  185. SharedPtr<Peer> p2p = _r->topology->getPeer(p2);
  186. if (!p2p)
  187. return false;
  188. uint64_t now = Utils::now();
  189. std::pair<InetAddress,InetAddress> cg(Peer::findCommonGround(*p1p,*p2p,now));
  190. if (!(cg.first))
  191. return false;
  192. // Addresses are sorted in key for last unite attempt map for order
  193. // invariant lookup: (p1,p2) == (p2,p1)
  194. Array<Address,2> uniteKey;
  195. if (p1 >= p2) {
  196. uniteKey[0] = p2;
  197. uniteKey[1] = p1;
  198. } else {
  199. uniteKey[0] = p1;
  200. uniteKey[1] = p2;
  201. }
  202. {
  203. Mutex::Lock _l(_lastUniteAttempt_m);
  204. std::map< Array< Address,2 >,uint64_t >::const_iterator e(_lastUniteAttempt.find(uniteKey));
  205. if ((!force)&&(e != _lastUniteAttempt.end())&&((now - e->second) < ZT_MIN_UNITE_INTERVAL))
  206. return false;
  207. else _lastUniteAttempt[uniteKey] = now;
  208. }
  209. TRACE("unite: %s(%s) <> %s(%s)",p1.toString().c_str(),cg.second.toString().c_str(),p2.toString().c_str(),cg.first.toString().c_str());
  210. { // tell p1 where to find p2
  211. Packet outp(p1,_r->identity.address(),Packet::VERB_RENDEZVOUS);
  212. outp.append(p2.data(),ZT_ADDRESS_LENGTH);
  213. outp.append((uint16_t)cg.first.port());
  214. if (cg.first.isV6()) {
  215. outp.append((unsigned char)16);
  216. outp.append(cg.first.rawIpData(),16);
  217. } else {
  218. outp.append((unsigned char)4);
  219. outp.append(cg.first.rawIpData(),4);
  220. }
  221. outp.encrypt(p1p->cryptKey());
  222. outp.hmacSet(p1p->macKey());
  223. p1p->send(_r,outp.data(),outp.size(),false,Packet::VERB_RENDEZVOUS,now);
  224. }
  225. { // tell p2 where to find p1
  226. Packet outp(p2,_r->identity.address(),Packet::VERB_RENDEZVOUS);
  227. outp.append(p1.data(),ZT_ADDRESS_LENGTH);
  228. outp.append((uint16_t)cg.second.port());
  229. if (cg.second.isV6()) {
  230. outp.append((unsigned char)16);
  231. outp.append(cg.second.rawIpData(),16);
  232. } else {
  233. outp.append((unsigned char)4);
  234. outp.append(cg.second.rawIpData(),4);
  235. }
  236. outp.encrypt(p2p->cryptKey());
  237. outp.hmacSet(p2p->macKey());
  238. p2p->send(_r,outp.data(),outp.size(),false,Packet::VERB_RENDEZVOUS,now);
  239. }
  240. return true;
  241. }
  242. unsigned long Switch::doTimerTasks()
  243. {
  244. unsigned long nextDelay = ~((unsigned long)0); // big number, caller will cap return value
  245. uint64_t now = Utils::now();
  246. {
  247. Mutex::Lock _l(_rendezvousQueue_m);
  248. for(std::map< Address,RendezvousQueueEntry >::iterator i(_rendezvousQueue.begin());i!=_rendezvousQueue.end();) {
  249. if (now >= i->second.fireAtTime) {
  250. SharedPtr<Peer> withPeer = _r->topology->getPeer(i->first);
  251. if (withPeer) {
  252. TRACE("sending NAT-T HELLO to %s(%s)",i->first.toString().c_str(),i->second.inaddr.toString().c_str());
  253. sendHELLO(withPeer,i->second.localPort,i->second.inaddr);
  254. }
  255. _rendezvousQueue.erase(i++);
  256. } else {
  257. nextDelay = std::min(nextDelay,(unsigned long)(i->second.fireAtTime - now));
  258. ++i;
  259. }
  260. }
  261. }
  262. {
  263. Mutex::Lock _l(_outstandingWhoisRequests_m);
  264. for(std::map< Address,WhoisRequest >::iterator i(_outstandingWhoisRequests.begin());i!=_outstandingWhoisRequests.end();) {
  265. unsigned long since = (unsigned long)(now - i->second.lastSent);
  266. if (since >= ZT_WHOIS_RETRY_DELAY) {
  267. if (i->second.retries >= ZT_MAX_WHOIS_RETRIES) {
  268. TRACE("WHOIS %s timed out",i->first.toString().c_str());
  269. _outstandingWhoisRequests.erase(i++);
  270. continue;
  271. } else {
  272. i->second.lastSent = now;
  273. i->second.peersConsulted[i->second.retries] = _sendWhoisRequest(i->first,i->second.peersConsulted,i->second.retries);
  274. ++i->second.retries;
  275. TRACE("WHOIS %s (retry %u)",i->first.toString().c_str(),i->second.retries);
  276. nextDelay = std::min(nextDelay,(unsigned long)ZT_WHOIS_RETRY_DELAY);
  277. }
  278. } else nextDelay = std::min(nextDelay,ZT_WHOIS_RETRY_DELAY - since);
  279. ++i;
  280. }
  281. }
  282. {
  283. Mutex::Lock _l(_txQueue_m);
  284. for(std::map< uint64_t,TXQueueEntry >::iterator i(_txQueue.begin());i!=_txQueue.end();) {
  285. if (_trySend(i->second.packet,i->second.encrypt))
  286. _txQueue.erase(i++);
  287. else if ((now - i->second.creationTime) > ZT_TRANSMIT_QUEUE_TIMEOUT) {
  288. TRACE("TX %s -> %s timed out",i->second.packet.source().toString().c_str(),i->second.packet.destination().toString().c_str());
  289. _txQueue.erase(i++);
  290. } else ++i;
  291. }
  292. }
  293. {
  294. Mutex::Lock _l(_rxQueue_m);
  295. for(std::map< uint64_t,RXQueueEntry >::iterator i(_rxQueue.begin());i!=_rxQueue.end();) {
  296. if (_tryHandleRemotePacket(i->second.localPort,i->second.fromAddr,i->second.packet))
  297. _rxQueue.erase(i++);
  298. else if ((now - i->second.creationTime) > ZT_RECEIVE_QUEUE_TIMEOUT) {
  299. TRACE("RX from %s timed out waiting for WHOIS",i->second.packet.source().toString().c_str());
  300. _rxQueue.erase(i++);
  301. } else ++i;
  302. }
  303. }
  304. {
  305. Mutex::Lock _l(_defragQueue_m);
  306. for(std::map< uint64_t,DefragQueueEntry >::iterator i(_defragQueue.begin());i!=_defragQueue.end();) {
  307. if ((now - i->second.creationTime) > ZT_FRAGMENTED_PACKET_RECEIVE_TIMEOUT) {
  308. TRACE("incomplete fragmented packet %.16llx timed out, fragments discarded",i->first);
  309. _defragQueue.erase(i++);
  310. } else ++i;
  311. }
  312. }
  313. return std::max(nextDelay,(unsigned long)50); // minimum delay
  314. }
  315. void Switch::announceMulticastGroups(const std::map< SharedPtr<Network>,std::set<MulticastGroup> > &allMemberships)
  316. {
  317. std::vector< SharedPtr<Peer> > directPeers;
  318. _r->topology->eachPeer(Topology::CollectPeersWithActiveDirectPath(directPeers));
  319. #ifdef ZT_TRACE
  320. unsigned int totalMulticastGroups = 0;
  321. for(std::map< SharedPtr<Network>,std::set<MulticastGroup> >::const_iterator i(allMemberships.begin());i!=allMemberships.end();++i)
  322. totalMulticastGroups += (unsigned int)i->second.size();
  323. TRACE("announcing %u multicast groups for %u networks to %u peers",totalMulticastGroups,(unsigned int)allMemberships.size(),(unsigned int)directPeers.size());
  324. #endif
  325. for(std::vector< SharedPtr<Peer> >::iterator p(directPeers.begin());p!=directPeers.end();++p) {
  326. Packet outp((*p)->address(),_r->identity.address(),Packet::VERB_MULTICAST_LIKE);
  327. for(std::map< SharedPtr<Network>,std::set<MulticastGroup> >::const_iterator nwmgs(allMemberships.begin());nwmgs!=allMemberships.end();++nwmgs) {
  328. if ((nwmgs->first->open())||(_r->topology->isSupernode((*p)->address()))||(nwmgs->first->isMember((*p)->address()))) {
  329. for(std::set<MulticastGroup>::iterator mg(nwmgs->second.begin());mg!=nwmgs->second.end();++mg) {
  330. if ((outp.size() + 18) > ZT_UDP_DEFAULT_PAYLOAD_MTU) {
  331. send(outp,true);
  332. outp.reset((*p)->address(),_r->identity.address(),Packet::VERB_MULTICAST_LIKE);
  333. }
  334. outp.append((uint64_t)nwmgs->first->id());
  335. outp.append(mg->mac().data,6);
  336. outp.append((uint32_t)mg->adi());
  337. }
  338. }
  339. }
  340. if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH)
  341. send(outp,true);
  342. }
  343. }
  344. void Switch::requestWhois(const Address &addr,const SharedPtr<PacketDecoder> &pd)
  345. {
  346. TRACE("requesting WHOIS for %s",addr.toString().c_str());
  347. _sendWhoisRequest(addr,(const Address *)0,0);
  348. Mutex::Lock _l(_outstandingWhoisRequests_m);
  349. std::pair< std::map< Address,WhoisRequest >::iterator,bool > entry(_outstandingWhoisRequests.insert(std::pair<Address,WhoisRequest>(addr,WhoisRequest())));
  350. entry.first->second.lastSent = Utils::now();
  351. entry.first->second.retries = 0; // reset retry count if entry already existed
  352. entry.first->second.waitingPackets.insert(pd);
  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); // terminate any outstanding WHOIS too
  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(
  406. const SharedPtr<Peer> &peer)
  407. {
  408. Mutex::Lock _l(_outstandingWhoisRequests_m);
  409. std::map< Address,WhoisRequest >::iterator wr(_outstandingWhoisRequests.find(peer->address()));
  410. if (wr != _outstandingWhoisRequests.end()) {
  411. for(std::set<uint64_t>::iterator pid(wr->second.waitingPackets.begin());pid!=wr->second.waitingPackets.end();++pid) {
  412. {
  413. Mutex::Lock _l(_txQueue_m);
  414. std::map< uint64_t,TXQueueEntry >::iterator txitem(_txQueue.find(*pid));
  415. if (txitem != _txQueue.end()) {
  416. if (_trySend(txitem->second.packet,txitem->second.encrypt))
  417. _txQueue.erase(txitem);
  418. }
  419. }
  420. {
  421. Mutex::Lock _l(_rxQueue_m);
  422. std::map< uint64_t,RXQueueEntry >::iterator rxitem(_rxQueue.find(*pid));
  423. if (rxitem != _rxQueue.end()) {
  424. if (_tryHandleRemotePacket(rxitem->second.localPort,rxitem->second.fromAddr,rxitem->second.packet))
  425. _rxQueue.erase(rxitem);
  426. }
  427. }
  428. }
  429. _outstandingWhoisRequests.erase(wr);
  430. }
  431. }
  432. void Switch::_handleRemotePacketFragment(Demarc::Port localPort,const InetAddress &fromAddr,const Buffer<4096> &data)
  433. {
  434. Packet::Fragment fragment(data);
  435. Address destination(fragment.destination());
  436. if (destination != _r->identity.address()) {
  437. // Fragment is not for us, so try to relay it
  438. if (fragment.hops() < ZT_RELAY_MAX_HOPS) {
  439. fragment.incrementHops();
  440. SharedPtr<Peer> relayTo = _r->topology->getPeer(destination);
  441. if ((!relayTo)||(!relayTo->send(_r,fragment.data(),fragment.size(),true,Packet::VERB_NOP,Utils::now()))) {
  442. relayTo = _r->topology->getBestSupernode();
  443. if (relayTo)
  444. relayTo->send(_r,fragment.data(),fragment.size(),true,Packet::VERB_NOP,Utils::now());
  445. }
  446. } else {
  447. TRACE("dropped relay [fragment](%s) -> %s, max hops exceeded",fromAddr.toString().c_str(),destination.toString().c_str());
  448. }
  449. } else {
  450. // Fragment looks like ours
  451. uint64_t pid = fragment.packetId();
  452. unsigned int fno = fragment.fragmentNumber();
  453. unsigned int tf = fragment.totalFragments();
  454. if ((tf <= ZT_MAX_PACKET_FRAGMENTS)&&(fno < ZT_MAX_PACKET_FRAGMENTS)&&(fno > 0)&&(tf > 1)) {
  455. // Fragment appears basically sane. Its fragment number must be
  456. // 1 or more, since a Packet with fragmented bit set is fragment 0.
  457. // Total fragments must be more than 1, otherwise why are we
  458. // seeing a Packet::Fragment?
  459. Mutex::Lock _l(_defragQueue_m);
  460. std::map< uint64_t,DefragQueueEntry >::iterator dqe(_defragQueue.find(pid));
  461. if (dqe == _defragQueue.end()) {
  462. // We received a Packet::Fragment without its head, so queue it and wait
  463. DefragQueueEntry &dq = _defragQueue[pid];
  464. dq.creationTime = Utils::now();
  465. dq.frags[fno - 1] = fragment;
  466. dq.totalFragments = tf; // total fragment count is known
  467. dq.haveFragments = 1 << fno; // we have only this fragment
  468. //TRACE("fragment (%u/%u) of %.16llx from %s",fno + 1,tf,pid,fromAddr.toString().c_str());
  469. } else if (!(dqe->second.haveFragments & (1 << fno))) {
  470. // We have other fragments and maybe the head, so add this one and check
  471. dqe->second.frags[fno - 1] = fragment;
  472. dqe->second.totalFragments = tf;
  473. //TRACE("fragment (%u/%u) of %.16llx from %s",fno + 1,tf,pid,fromAddr.toString().c_str());
  474. if (Utils::countBits(dqe->second.haveFragments |= (1 << fno)) == tf) {
  475. // We have all fragments -- assemble and process full Packet
  476. //TRACE("packet %.16llx is complete, assembling and processing...",pid);
  477. Packet packet(dqe->second.frag0);
  478. for(unsigned int f=1;f<tf;++f)
  479. packet.append(dqe->second.frags[f - 1].payload(),dqe->second.frags[f - 1].payloadLength());
  480. _defragQueue.erase(dqe);
  481. _handleRemotePacket(localPort,fromAddr,packet);
  482. }
  483. } // else this is a duplicate fragment, ignore
  484. }
  485. }
  486. }
  487. bool Switch::_handleRemotePacketHead(Demarc::Port localPort,const InetAddress &fromAddr,const Buffer<4096> &data)
  488. {
  489. Packet packet(data);
  490. Address destination(packet.destination());
  491. if (destination != _r->identity.address()) {
  492. // Packet is not for us, so try to relay it
  493. if (packet.hops() < ZT_RELAY_MAX_HOPS) {
  494. packet.incrementHops();
  495. SharedPtr<Peer> relayTo = _r->topology->getPeer(destination);
  496. if ((relayTo)&&(relayTo->send(_r,packet.data(),packet.size(),true,Packet::VERB_NOP,Utils::now()))) {
  497. // TODO: don't unite immediately, wait until the peers have exchanged a packet or two
  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. _handleRemotePacket(localPort,fromAddr,packet);
  530. } else {
  531. // Still waiting on more fragments, so queue the head
  532. dqe->second.frag0 = packet;
  533. }
  534. } // else this is a duplicate head, ignore
  535. } else {
  536. // Packet is unfragmented, so just process it
  537. _handleRemotePacket(localPort,fromAddr,packet);
  538. }
  539. }
  540. //////////////////// OBSOLETE
  541. bool Switch::_tryHandleRemotePacket(Demarc::Port localPort,const InetAddress &fromAddr,Packet &packet)
  542. {
  543. Address source(packet.source());
  544. if ((!packet.encrypted())&&(packet.verb() == Packet::VERB_HELLO)) {
  545. // Unencrypted HELLOs are handled here since they are used to
  546. // populate our identity cache in the first place. Thus we might get
  547. // a HELLO for someone for whom we don't have a Peer record.
  548. TRACE("HELLO from %s(%s)",source.toString().c_str(),fromAddr.toString().c_str());
  549. _doHELLO(localPort,fromAddr,packet);
  550. return true;
  551. }
  552. SharedPtr<Peer> peer = _r->topology->getPeer(source);
  553. if (peer) {
  554. uint64_t now = Utils::now();
  555. unsigned int latency = 0;
  556. if (!packet.hmacVerify(peer->macKey())) {
  557. TRACE("dropped packet from %s(%s), HMAC authentication failed (size: %u)",source.toString().c_str(),fromAddr.toString().c_str(),packet.size());
  558. return true;
  559. }
  560. if (packet.encrypted()) {
  561. packet.decrypt(peer->cryptKey());
  562. } else {
  563. // Unencrypted is tolerated in case we want to run this on
  564. // devices where squeezing out cycles matters. HMAC is
  565. // what's really important.
  566. TRACE("ODD: %s from %s(%s) wasn't encrypted",Packet::verbString(packet.verb()),source.toString().c_str(),fromAddr.toString().c_str());
  567. }
  568. if (!packet.uncompress()) {
  569. TRACE("dropped packet from %s(%s), compressed data invalid",source.toString().c_str(),fromAddr.toString().c_str());
  570. return true;
  571. }
  572. switch(packet.verb()) {
  573. case Packet::VERB_NOP:
  574. TRACE("NOP from %s(%s)",source.toString().c_str(),fromAddr.toString().c_str());
  575. break;
  576. case Packet::VERB_HELLO:
  577. // HELLO is normally handled up top, but this is legal. Pointless, but legal.
  578. _doHELLO(localPort,fromAddr,packet);
  579. break;
  580. case Packet::VERB_ERROR:
  581. try {
  582. #ifdef ZT_TRACE
  583. Packet::Verb inReVerb = (Packet::Verb)packet[ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB];
  584. Packet::ErrorCode errorCode = (Packet::ErrorCode)packet[ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE];
  585. TRACE("ERROR %s from %s(%s) in-re %s",Packet::errorString(errorCode),source.toString().c_str(),fromAddr.toString().c_str(),Packet::verbString(inReVerb));
  586. #endif
  587. // TODO:
  588. // The fact is that the protocol works fine without error handling.
  589. // The only error that really needs to be handled here is duplicate
  590. // identity collision, which if it comes from a supernode should cause
  591. // us to restart and regenerate a new identity.
  592. } catch (std::exception &ex) {
  593. TRACE("dropped ERROR from %s(%s): unexpected exception: %s",source.toString().c_str(),fromAddr.toString().c_str(),ex.what());
  594. } catch ( ... ) {
  595. TRACE("dropped ERROR from %s(%s): unexpected exception: (unknown)",source.toString().c_str(),fromAddr.toString().c_str());
  596. }
  597. break;
  598. case Packet::VERB_OK:
  599. try {
  600. Packet::Verb inReVerb = (Packet::Verb)packet[ZT_PROTO_VERB_OK_IDX_IN_RE_VERB];
  601. switch(inReVerb) {
  602. case Packet::VERB_HELLO:
  603. // OK from HELLO permits computation of latency.
  604. latency = std::min((unsigned int)(now - packet.at<uint64_t>(ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP)),(unsigned int)0xffff);
  605. TRACE("%s(%s): OK(HELLO), latency: %u",source.toString().c_str(),fromAddr.toString().c_str(),latency);
  606. break;
  607. case Packet::VERB_WHOIS:
  608. // Right now we only query supernodes for WHOIS and only accept
  609. // OK back from them. If we query other nodes, we'll have to
  610. // do something to prevent WHOIS cache poisoning such as
  611. // using the packet ID field in the OK packet to match with the
  612. // original query. Technically we should be doing this anyway.
  613. TRACE("%s(%s): OK(%s)",source.toString().c_str(),fromAddr.toString().c_str(),Packet::verbString(inReVerb));
  614. if (_r->topology->isSupernode(source))
  615. _r->topology->addPeer(SharedPtr<Peer>(new Peer(_r->identity,Identity(packet,ZT_PROTO_VERB_WHOIS__OK__IDX_IDENTITY))),&Switch::_CBaddPeerFromWhois,this);
  616. break;
  617. default:
  618. TRACE("%s(%s): OK(%s)",source.toString().c_str(),fromAddr.toString().c_str(),Packet::verbString(inReVerb));
  619. break;
  620. }
  621. } catch (std::exception &ex) {
  622. TRACE("dropped OK from %s(%s): unexpected exception: %s",source.toString().c_str(),fromAddr.toString().c_str(),ex.what());
  623. } catch ( ... ) {
  624. TRACE("dropped OK from %s(%s): unexpected exception: (unknown)",source.toString().c_str(),fromAddr.toString().c_str());
  625. }
  626. break;
  627. case Packet::VERB_WHOIS:
  628. if (packet.payloadLength() == ZT_ADDRESS_LENGTH) {
  629. SharedPtr<Peer> p(_r->topology->getPeer(Address(packet.payload())));
  630. if (p) {
  631. Packet outp(source,_r->identity.address(),Packet::VERB_OK);
  632. outp.append((unsigned char)Packet::VERB_WHOIS);
  633. outp.append(packet.packetId());
  634. p->identity().serialize(outp,false);
  635. outp.encrypt(peer->cryptKey());
  636. outp.hmacSet(peer->macKey());
  637. _r->demarc->send(localPort,fromAddr,outp.data(),outp.size(),-1);
  638. TRACE("sent WHOIS response to %s for %s",source.toString().c_str(),Address(packet.payload()).toString().c_str());
  639. } else {
  640. Packet outp(source,_r->identity.address(),Packet::VERB_ERROR);
  641. outp.append((unsigned char)Packet::VERB_WHOIS);
  642. outp.append(packet.packetId());
  643. outp.append((unsigned char)Packet::ERROR_NOT_FOUND);
  644. outp.append(packet.payload(),ZT_ADDRESS_LENGTH);
  645. outp.encrypt(peer->cryptKey());
  646. outp.hmacSet(peer->macKey());
  647. _r->demarc->send(localPort,fromAddr,outp.data(),outp.size(),-1);
  648. TRACE("sent WHOIS ERROR to %s for %s (not found)",source.toString().c_str(),Address(packet.payload()).toString().c_str());
  649. }
  650. } else {
  651. TRACE("dropped WHOIS from %s(%s): missing or invalid address",source.toString().c_str(),fromAddr.toString().c_str());
  652. }
  653. break;
  654. case Packet::VERB_RENDEZVOUS:
  655. try {
  656. Address with(packet.field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS,ZT_ADDRESS_LENGTH));
  657. RendezvousQueueEntry qe;
  658. if (_r->topology->getPeer(with)) {
  659. unsigned int port = packet.at<uint16_t>(ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT);
  660. unsigned int addrlen = packet[ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN];
  661. if ((port > 0)&&((addrlen == 4)||(addrlen == 16))) {
  662. qe.inaddr.set(packet.field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS,addrlen),addrlen,port);
  663. qe.fireAtTime = now + ZT_RENDEZVOUS_NAT_T_DELAY; // then send real packet in a few ms
  664. qe.localPort = _r->demarc->pick(qe.inaddr);
  665. TRACE("RENDEZVOUS from %s says %s might be at %s, starting NAT-t",source.toString().c_str(),with.toString().c_str(),qe.inaddr.toString().c_str());
  666. _r->demarc->send(qe.localPort,qe.inaddr,"\0",1,ZT_FIREWALL_OPENER_HOPS); // start with firewall opener
  667. {
  668. Mutex::Lock _l(_rendezvousQueue_m);
  669. _rendezvousQueue[with] = qe;
  670. }
  671. } else {
  672. TRACE("dropped corrupt RENDEZVOUS from %s(%s) (bad address or port)",source.toString().c_str(),fromAddr.toString().c_str());
  673. }
  674. } else {
  675. TRACE("ignored RENDEZVOUS from %s(%s) to meet unknown peer %s",source.toString().c_str(),fromAddr.toString().c_str(),with.toString().c_str());
  676. }
  677. } catch (std::exception &ex) {
  678. TRACE("dropped RENDEZVOUS from %s(%s): %s",source.toString().c_str(),fromAddr.toString().c_str(),ex.what());
  679. } catch ( ... ) {
  680. TRACE("dropped RENDEZVOUS from %s(%s): unexpected exception",source.toString().c_str(),fromAddr.toString().c_str());
  681. }
  682. break;
  683. case Packet::VERB_FRAME:
  684. try {
  685. SharedPtr<Network> network(_r->nc->network(packet.at<uint64_t>(ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID)));
  686. if (network) {
  687. if (network->isAllowed(source)) {
  688. unsigned int etherType = packet.at<uint16_t>(ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE);
  689. if ((etherType != ZT_ETHERTYPE_ARP)&&(etherType != ZT_ETHERTYPE_IPV4)&&(etherType != ZT_ETHERTYPE_IPV6)) {
  690. TRACE("dropped FRAME from %s: unsupported ethertype",source.toString().c_str());
  691. } else if (packet.size() > ZT_PROTO_VERB_FRAME_IDX_PAYLOAD) {
  692. network->tap().put(source.toMAC(),network->tap().mac(),etherType,packet.data() + ZT_PROTO_VERB_FRAME_IDX_PAYLOAD,packet.size() - ZT_PROTO_VERB_FRAME_IDX_PAYLOAD);
  693. }
  694. } else {
  695. TRACE("dropped FRAME from %s(%s): not a member of closed network %llu",source.toString().c_str(),fromAddr.toString().c_str(),network->id());
  696. }
  697. } else {
  698. TRACE("dropped FRAME from %s(%s): network %llu unknown",source.toString().c_str(),fromAddr.toString().c_str(),packet.at<uint64_t>(ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID));
  699. }
  700. } catch (std::exception &ex) {
  701. TRACE("dropped FRAME from %s(%s): unexpected exception: %s",source.toString().c_str(),fromAddr.toString().c_str(),ex.what());
  702. } catch ( ... ) {
  703. TRACE("dropped FRAME from %s(%s): unexpected exception: (unknown)",source.toString().c_str(),fromAddr.toString().c_str());
  704. }
  705. break;
  706. case Packet::VERB_MULTICAST_LIKE:
  707. try {
  708. unsigned int ptr = ZT_PACKET_IDX_PAYLOAD;
  709. unsigned int numAccepted = 0;
  710. // Iterate through 18-byte network,MAC,ADI tuples:
  711. while ((ptr + 18) <= packet.size()) {
  712. uint64_t nwid = packet.at<uint64_t>(ptr); ptr += 8;
  713. SharedPtr<Network> network(_r->nc->network(nwid));
  714. if (network) {
  715. if (network->isAllowed(source)) {
  716. MAC mac(packet.field(ptr,6)); ptr += 6;
  717. uint32_t adi = packet.at<uint32_t>(ptr); ptr += 4;
  718. TRACE("peer %s likes multicast group %s:%.8lx on network %llu",source.toString().c_str(),mac.toString().c_str(),(unsigned long)adi,nwid);
  719. _multicaster.likesMulticastGroup(nwid,MulticastGroup(mac,adi),source,now);
  720. ++numAccepted;
  721. } else {
  722. TRACE("ignored MULTICAST_LIKE from %s(%s): not a member of closed network %llu",source.toString().c_str(),fromAddr.toString().c_str(),nwid);
  723. }
  724. } else {
  725. TRACE("ignored MULTICAST_LIKE from %s(%s): network %llu unknown or we are not a member",source.toString().c_str(),fromAddr.toString().c_str(),nwid);
  726. }
  727. }
  728. Packet outp(source,_r->identity.address(),Packet::VERB_OK);
  729. outp.append((unsigned char)Packet::VERB_MULTICAST_LIKE);
  730. outp.append(packet.packetId());
  731. outp.append((uint16_t)numAccepted);
  732. outp.encrypt(peer->cryptKey());
  733. outp.hmacSet(peer->macKey());
  734. _r->demarc->send(localPort,fromAddr,outp.data(),outp.size(),-1);
  735. } catch (std::exception &ex) {
  736. TRACE("dropped MULTICAST_LIKE from %s(%s): unexpected exception: %s",source.toString().c_str(),fromAddr.toString().c_str(),ex.what());
  737. } catch ( ... ) {
  738. TRACE("dropped MULTICAST_LIKE from %s(%s): unexpected exception: (unknown)",source.toString().c_str(),fromAddr.toString().c_str());
  739. }
  740. break;
  741. case Packet::VERB_MULTICAST_FRAME:
  742. try {
  743. SharedPtr<Network> network(_r->nc->network(packet.at<uint64_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID)));
  744. if (network) {
  745. if (network->isAllowed(source)) {
  746. if (packet.size() > ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PAYLOAD) {
  747. Address originalSubmitterAddress(packet.field(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SUBMITTER_ADDRESS,ZT_ADDRESS_LENGTH));
  748. MAC fromMac(packet.field(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SOURCE_MAC,6));
  749. MulticastGroup mg(MAC(packet.field(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DESTINATION_MAC,6)),packet.at<uint32_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ADI));
  750. unsigned int hops = packet[ZT_PROTO_VERB_MULTICAST_FRAME_IDX_HOP_COUNT];
  751. unsigned int etherType = packet.at<uint16_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE);
  752. unsigned int datalen = packet.at<uint16_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PAYLOAD_LENGTH);
  753. unsigned int signaturelen = packet.at<uint16_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SIGNATURE_LENGTH);
  754. unsigned char *dataAndSignature = packet.field(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PAYLOAD,datalen + signaturelen);
  755. bool isDuplicate = _multicaster.checkAndUpdateMulticastHistory(fromMac,mg,payload,payloadLen,network->id(),now);
  756. if (originalSubmitterAddress == _r->identity.address()) {
  757. // Technically should not happen, since the original submitter is
  758. // excluded from consideration as a propagation recipient.
  759. TRACE("dropped boomerang MULTICAST_FRAME received from %s(%s)",source.toString().c_str(),fromAddr.toString().c_str());
  760. } else if ((!isDuplicate)||(_r->topology.isSupernode(_r->identity.address()))) {
  761. // If I am a supernode, I will repeatedly propagate duplicates. That's
  762. // because supernodes are used to bridge sparse multicast groups. Non-
  763. // supernodes will ignore duplicates completely.
  764. SharedPtr<Peer> originalSubmitter(_r->topology->getPeer(originalSubmitterAddress));
  765. if (!originalSubmitter) {
  766. TRACE("requesting WHOIS on original multicast frame submitter %s",originalSubmitterAddress.toString().c_str());
  767. _requestWhois(originalSubmitterAddress,packet.packetId());
  768. return false;
  769. } else if (Multicaster::verifyMulticastPacket(originalSubmitter->identity(),fromMac,mg,etherType,data,datalen,dataAndSignature + datalen,signaturelen)) {
  770. if (!isDuplicate)
  771. network->tap().put(fromMac,mg.mac(),etherType,payload,payloadLen);
  772. _propagateMulticast(network,originalSubmitterAddress,source,packet.field(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_BLOOM,ZT_PROTO_VERB_MULTICAST_FRAME_BLOOM_FILTER_SIZE),mg,hops+1,fromMac,etherType,payload,payloadLen);
  773. } else {
  774. LOG("rejected MULTICAST_FRAME from %s(%s) due to failed signature check (claims original sender %s)",source.toString().c_str(),fromAddr.toString().c_str(),originalSubmitterAddress.toString().c_str());
  775. }
  776. } else {
  777. TRACE("dropped redundant MULTICAST_FRAME from %s(%s)",source.toString().c_str(),fromAddr.toString().c_str());
  778. }
  779. } else {
  780. TRACE("dropped MULTICAST_FRAME from %s(%s): invalid short packet",source.toString().c_str(),fromAddr.toString().c_str());
  781. }
  782. } else {
  783. TRACE("dropped MULTICAST_FRAME from %s(%s): not a member of closed network %llu",source.toString().c_str(),fromAddr.toString().c_str(),network->id());
  784. }
  785. } else {
  786. TRACE("dropped MULTICAST_FRAME from %s(%s): network %llu unknown or we are not a member",source.toString().c_str(),fromAddr.toString().c_str(),packet.at<uint64_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID));
  787. }
  788. } catch (std::exception &ex) {
  789. TRACE("dropped MULTICAST_FRAME from %s(%s): unexpected exception: %s",source.toString().c_str(),fromAddr.toString().c_str(),ex.what());
  790. } catch ( ... ) {
  791. TRACE("dropped MULTICAST_FRAME from %s(%s): unexpected exception: (unknown)",source.toString().c_str(),fromAddr.toString().c_str());
  792. }
  793. break;
  794. default:
  795. // This might be something from a new or old version of the protocol.
  796. // Technically it passed HMAC so the packet is still valid, but we
  797. // ignore it.
  798. TRACE("ignored unrecognized verb %.2x from %s(%s)",(unsigned int)packet.verb(),source.toString().c_str(),fromAddr.toString().c_str());
  799. break;
  800. }
  801. // Update peer timestamps and learn new links. This must only ever
  802. // be called on an authenticated and technically valid packet, since
  803. // we only learn paths to peers over the WAN by hearing directly
  804. // from them over those paths. (Or by having them authoritatively
  805. // and statically defined, like with supernodes, but that's done
  806. // elsewhere.)
  807. peer->onReceive(_r,localPort,fromAddr,latency,packet.hops(),packet.verb(),now);
  808. } else {
  809. _requestWhois(source,packet.packetId());
  810. return false;
  811. }
  812. return true;
  813. }
  814. void Switch::_doHELLO(Demarc::Port localPort,const InetAddress &fromAddr,Packet &packet)
  815. {
  816. Address source(packet.source());
  817. try {
  818. unsigned int protoVersion = packet[ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION];
  819. unsigned int vMajor = packet[ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION];
  820. unsigned int vMinor = packet[ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION];
  821. unsigned int vRevision = packet.at<uint16_t>(ZT_PROTO_VERB_HELLO_IDX_REVISION);
  822. uint64_t timestamp = packet.at<uint64_t>(ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP);
  823. Identity id(packet,ZT_PROTO_VERB_HELLO_IDX_IDENTITY);
  824. SharedPtr<Peer> candidate(new Peer(_r->identity,id));
  825. candidate->setPathAddress(fromAddr,false);
  826. // Initial sniff test
  827. if (protoVersion != ZT_PROTO_VERSION) {
  828. TRACE("rejected HELLO from %s(%s): invalid protocol version",source.toString().c_str(),fromAddr.toString().c_str());
  829. Packet outp(source,_r->identity.address(),Packet::VERB_ERROR);
  830. outp.append((unsigned char)Packet::VERB_HELLO);
  831. outp.append(packet.packetId());
  832. outp.append((unsigned char)Packet::ERROR_BAD_PROTOCOL_VERSION);
  833. outp.encrypt(candidate->cryptKey());
  834. outp.hmacSet(candidate->macKey());
  835. _r->demarc->send(localPort,fromAddr,outp.data(),outp.size(),-1);
  836. return;
  837. }
  838. if (id.address().isReserved()) {
  839. TRACE("rejected HELLO from %s(%s): identity has reserved address",source.toString().c_str(),fromAddr.toString().c_str());
  840. Packet outp(source,_r->identity.address(),Packet::VERB_ERROR);
  841. outp.append((unsigned char)Packet::VERB_HELLO);
  842. outp.append(packet.packetId());
  843. outp.append((unsigned char)Packet::ERROR_IDENTITY_INVALID);
  844. outp.encrypt(candidate->cryptKey());
  845. outp.hmacSet(candidate->macKey());
  846. _r->demarc->send(localPort,fromAddr,outp.data(),outp.size(),-1);
  847. return;
  848. }
  849. if (id.address() != source) {
  850. TRACE("rejected HELLO from %s(%s): identity is not for sender of packet (HELLO is a self-announcement)",source.toString().c_str(),fromAddr.toString().c_str());
  851. Packet outp(source,_r->identity.address(),Packet::VERB_ERROR);
  852. outp.append((unsigned char)Packet::VERB_HELLO);
  853. outp.append(packet.packetId());
  854. outp.append((unsigned char)Packet::ERROR_INVALID_REQUEST);
  855. outp.encrypt(candidate->cryptKey());
  856. outp.hmacSet(candidate->macKey());
  857. _r->demarc->send(localPort,fromAddr,outp.data(),outp.size(),-1);
  858. return;
  859. }
  860. // Is this a HELLO for a peer we already know? If so just update its
  861. // packet receive stats and send an OK.
  862. SharedPtr<Peer> existingPeer(_r->topology->getPeer(id.address()));
  863. if ((existingPeer)&&(existingPeer->identity() == id)) {
  864. existingPeer->onReceive(_r,localPort,fromAddr,0,packet.hops(),Packet::VERB_HELLO,Utils::now());
  865. Packet outp(source,_r->identity.address(),Packet::VERB_OK);
  866. outp.append((unsigned char)Packet::VERB_HELLO);
  867. outp.append(packet.packetId());
  868. outp.append(timestamp);
  869. outp.encrypt(existingPeer->cryptKey());
  870. outp.hmacSet(existingPeer->macKey());
  871. _r->demarc->send(localPort,fromAddr,outp.data(),outp.size(),-1);
  872. return;
  873. }
  874. // Otherwise we call addPeer() and set up a callback to handle the verdict
  875. _CBaddPeerFromHello_Data *arg = new _CBaddPeerFromHello_Data;
  876. arg->parent = this;
  877. arg->source = source;
  878. arg->fromAddr = fromAddr;
  879. arg->localPort = localPort;
  880. arg->vMajor = vMajor;
  881. arg->vMinor = vMinor;
  882. arg->vRevision = vRevision;
  883. arg->helloPacketId = packet.packetId();
  884. arg->helloTimestamp = timestamp;
  885. _r->topology->addPeer(candidate,&Switch::_CBaddPeerFromHello,arg);
  886. } catch (std::exception &ex) {
  887. TRACE("dropped HELLO from %s(%s): %s",source.toString().c_str(),fromAddr.toString().c_str(),ex.what());
  888. } catch ( ... ) {
  889. TRACE("dropped HELLO from %s(%s): unexpected exception",source.toString().c_str(),fromAddr.toString().c_str());
  890. }
  891. }
  892. Address Switch::_sendWhoisRequest(const Address &addr,const Address *peersAlreadyConsulted,unsigned int numPeersAlreadyConsulted)
  893. {
  894. SharedPtr<Peer> supernode(_r->topology->getBestSupernode(peersAlreadyConsulted,numPeersAlreadyConsulted));
  895. if (supernode) {
  896. Packet outp(supernode->address(),_r->identity.address(),Packet::VERB_WHOIS);
  897. outp.append(addr.data(),ZT_ADDRESS_LENGTH);
  898. outp.encrypt(supernode->cryptKey());
  899. outp.hmacSet(supernode->macKey());
  900. supernode->send(_r,outp.data(),outp.size(),false,Packet::VERB_WHOIS,Utils::now());
  901. return supernode->address();
  902. }
  903. return Address();
  904. }
  905. bool Switch::_trySend(const Packet &packet,bool encrypt)
  906. {
  907. SharedPtr<Peer> peer(_r->topology->getPeer(packet.destination()));
  908. if (peer) {
  909. uint64_t now = Utils::now();
  910. bool isRelay;
  911. SharedPtr<Peer> via;
  912. if ((_r->topology->isSupernode(peer->address()))||(peer->hasActiveDirectPath(now))) {
  913. isRelay = false;
  914. via = peer;
  915. } else {
  916. isRelay = true;
  917. via = _r->topology->getBestSupernode();
  918. if (!via)
  919. return false;
  920. }
  921. Packet tmp(packet);
  922. unsigned int chunkSize = std::min(tmp.size(),(unsigned int)ZT_UDP_DEFAULT_PAYLOAD_MTU);
  923. tmp.setFragmented(chunkSize < tmp.size());
  924. if (encrypt)
  925. tmp.encrypt(peer->cryptKey());
  926. tmp.hmacSet(peer->macKey());
  927. Packet::Verb verb = packet.verb();
  928. if (via->send(_r,tmp.data(),chunkSize,isRelay,verb,now)) {
  929. if (chunkSize < tmp.size()) {
  930. // Too big for one bite, fragment the rest
  931. unsigned int fragStart = chunkSize;
  932. unsigned int remaining = tmp.size() - chunkSize;
  933. unsigned int fragsRemaining = (remaining / (ZT_UDP_DEFAULT_PAYLOAD_MTU - ZT_PROTO_MIN_FRAGMENT_LENGTH));
  934. if ((fragsRemaining * (ZT_UDP_DEFAULT_PAYLOAD_MTU - ZT_PROTO_MIN_FRAGMENT_LENGTH)) < remaining)
  935. ++fragsRemaining;
  936. unsigned int totalFragments = fragsRemaining + 1;
  937. for(unsigned int f=0;f<fragsRemaining;++f) {
  938. chunkSize = std::min(remaining,(unsigned int)(ZT_UDP_DEFAULT_PAYLOAD_MTU - ZT_PROTO_MIN_FRAGMENT_LENGTH));
  939. Packet::Fragment frag(tmp,fragStart,chunkSize,f + 1,totalFragments);
  940. if (!via->send(_r,frag.data(),frag.size(),isRelay,verb,now)) {
  941. TRACE("WARNING: packet send to %s failed on later fragment #%u (check IP layer buffer sizes?)",via->address().toString().c_str(),f + 1);
  942. return false;
  943. }
  944. fragStart += chunkSize;
  945. remaining -= chunkSize;
  946. }
  947. }
  948. return true;
  949. }
  950. return false;
  951. }
  952. _requestWhois(packet.destination(),packet.packetId());
  953. return false;
  954. }
  955. } // namespace ZeroTier