IncomingPacket.cpp 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2019 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. * --
  19. *
  20. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #include <stdio.h>
  27. #include <string.h>
  28. #include <stdlib.h>
  29. #include <list>
  30. #include "../include/ZeroTierOne.h"
  31. #include "Constants.hpp"
  32. #include "RuntimeEnvironment.hpp"
  33. #include "IncomingPacket.hpp"
  34. #include "Topology.hpp"
  35. #include "Switch.hpp"
  36. #include "Peer.hpp"
  37. #include "NetworkController.hpp"
  38. #include "SelfAwareness.hpp"
  39. #include "Salsa20.hpp"
  40. #include "Node.hpp"
  41. #include "CertificateOfMembership.hpp"
  42. #include "Capability.hpp"
  43. #include "Tag.hpp"
  44. #include "Revocation.hpp"
  45. #include "Trace.hpp"
  46. namespace ZeroTier {
  47. bool IncomingPacket::tryDecode(const RuntimeEnvironment *RR,void *tPtr)
  48. {
  49. const Address sourceAddress(source());
  50. try {
  51. // Check for trusted paths or unencrypted HELLOs (HELLO is the only packet sent in the clear)
  52. const unsigned int c = cipher();
  53. bool trusted = false;
  54. if (c == ZT_PROTO_CIPHER_SUITE__NO_CRYPTO_TRUSTED_PATH) {
  55. // If this is marked as a packet via a trusted path, check source address and path ID.
  56. // Obviously if no trusted paths are configured this always returns false and such
  57. // packets are dropped on the floor.
  58. const uint64_t tpid = trustedPathId();
  59. if (RR->topology->shouldInboundPathBeTrusted(_path->address(),tpid)) {
  60. trusted = true;
  61. } else {
  62. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,packetId(),sourceAddress,hops(),"path not trusted");
  63. return true;
  64. }
  65. } else if ((c == ZT_PROTO_CIPHER_SUITE__POLY1305_NONE)&&(verb() == Packet::VERB_HELLO)) {
  66. // Only HELLO is allowed in the clear, but will still have a MAC
  67. return _doHELLO(RR,tPtr,false);
  68. }
  69. const SharedPtr<Peer> peer(RR->topology->get(sourceAddress));
  70. if (peer) {
  71. if (!trusted) {
  72. if (!dearmor(peer->key())) {
  73. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,packetId(),sourceAddress,hops(),"invalid MAC");
  74. _path->recordInvalidPacket();
  75. return true;
  76. }
  77. }
  78. if (!uncompress()) {
  79. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),sourceAddress,hops(),Packet::VERB_NOP,"LZ4 decompression failed");
  80. return true;
  81. }
  82. const Packet::Verb v = verb();
  83. bool r = true;
  84. switch(v) {
  85. //case Packet::VERB_NOP:
  86. default: // ignore unknown verbs, but if they pass auth check they are "received"
  87. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),v,0,Packet::VERB_NOP,0);
  88. break;
  89. case Packet::VERB_HELLO: r = _doHELLO(RR,tPtr,true); break;
  90. case Packet::VERB_ACK: r = _doACK(RR,tPtr,peer); break;
  91. case Packet::VERB_QOS_MEASUREMENT: r = _doQOS_MEASUREMENT(RR,tPtr,peer); break;
  92. case Packet::VERB_ERROR: r = _doERROR(RR,tPtr,peer); break;
  93. case Packet::VERB_OK: r = _doOK(RR,tPtr,peer); break;
  94. case Packet::VERB_WHOIS: r = _doWHOIS(RR,tPtr,peer); break;
  95. case Packet::VERB_RENDEZVOUS: r = _doRENDEZVOUS(RR,tPtr,peer); break;
  96. case Packet::VERB_FRAME: r = _doFRAME(RR,tPtr,peer); break;
  97. case Packet::VERB_EXT_FRAME: r = _doEXT_FRAME(RR,tPtr,peer); break;
  98. case Packet::VERB_ECHO: r = _doECHO(RR,tPtr,peer); break;
  99. case Packet::VERB_MULTICAST_LIKE: r = _doMULTICAST_LIKE(RR,tPtr,peer); break;
  100. case Packet::VERB_NETWORK_CREDENTIALS: r = _doNETWORK_CREDENTIALS(RR,tPtr,peer); break;
  101. case Packet::VERB_NETWORK_CONFIG_REQUEST: r = _doNETWORK_CONFIG_REQUEST(RR,tPtr,peer); break;
  102. case Packet::VERB_NETWORK_CONFIG: r = _doNETWORK_CONFIG(RR,tPtr,peer); break;
  103. case Packet::VERB_MULTICAST_GATHER: r = _doMULTICAST_GATHER(RR,tPtr,peer); break;
  104. case Packet::VERB_MULTICAST_FRAME: r = _doMULTICAST_FRAME(RR,tPtr,peer); break;
  105. case Packet::VERB_PUSH_DIRECT_PATHS: r = _doPUSH_DIRECT_PATHS(RR,tPtr,peer); break;
  106. case Packet::VERB_USER_MESSAGE: r = _doUSER_MESSAGE(RR,tPtr,peer); break;
  107. case Packet::VERB_REMOTE_TRACE: r = _doREMOTE_TRACE(RR,tPtr,peer); break;
  108. }
  109. return r;
  110. } else {
  111. RR->sw->requestWhois(tPtr,RR->node->now(),sourceAddress);
  112. return false;
  113. }
  114. } catch ( ... ) {
  115. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),sourceAddress,hops(),verb(),"unexpected exception in tryDecode()");
  116. return true;
  117. }
  118. }
  119. bool IncomingPacket::_doERROR(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  120. {
  121. const Packet::Verb inReVerb = (Packet::Verb)(*this)[ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB];
  122. const uint64_t inRePacketId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID);
  123. const Packet::ErrorCode errorCode = (Packet::ErrorCode)(*this)[ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE];
  124. uint64_t networkId = 0;
  125. /* Security note: we do not gate doERROR() with expectingReplyTo() to
  126. * avoid having to log every outgoing packet ID. Instead we put the
  127. * logic to determine whether we should consider an ERROR in each
  128. * error handler. In most cases these are only trusted in specific
  129. * circumstances. */
  130. switch(errorCode) {
  131. case Packet::ERROR_OBJ_NOT_FOUND:
  132. // Object not found, currently only meaningful from network controllers.
  133. if (inReVerb == Packet::VERB_NETWORK_CONFIG_REQUEST) {
  134. networkId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD);
  135. const SharedPtr<Network> network(RR->node->network(networkId));
  136. if ((network)&&(network->controller() == peer->address()))
  137. network->setNotFound();
  138. }
  139. break;
  140. case Packet::ERROR_UNSUPPORTED_OPERATION:
  141. // This can be sent in response to any operation, though right now we only
  142. // consider it meaningful from network controllers. This would indicate
  143. // that the queried node does not support acting as a controller.
  144. if (inReVerb == Packet::VERB_NETWORK_CONFIG_REQUEST) {
  145. networkId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD);
  146. const SharedPtr<Network> network(RR->node->network(networkId));
  147. if ((network)&&(network->controller() == peer->address()))
  148. network->setNotFound();
  149. }
  150. break;
  151. case Packet::ERROR_NEED_MEMBERSHIP_CERTIFICATE: {
  152. // Peers can send this to ask for a cert for a network.
  153. networkId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD);
  154. const SharedPtr<Network> network(RR->node->network(networkId));
  155. const int64_t now = RR->node->now();
  156. if ((network)&&(network->config().com))
  157. network->pushCredentialsNow(tPtr,peer->address(),now);
  158. } break;
  159. case Packet::ERROR_NETWORK_ACCESS_DENIED_: {
  160. // Network controller: network access denied.
  161. networkId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD);
  162. const SharedPtr<Network> network(RR->node->network(networkId));
  163. if ((network)&&(network->controller() == peer->address()))
  164. network->setAccessDenied();
  165. } break;
  166. case Packet::ERROR_UNWANTED_MULTICAST: {
  167. // Members of networks can use this error to indicate that they no longer
  168. // want to receive multicasts on a given channel.
  169. networkId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD);
  170. const SharedPtr<Network> network(RR->node->network(networkId));
  171. if ((network)&&(network->gate(tPtr,peer))) {
  172. const MulticastGroup mg(MAC(field(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD + 8,6),6),at<uint32_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD + 14));
  173. RR->mc->remove(network->id(),mg,peer->address());
  174. }
  175. } break;
  176. default: break;
  177. }
  178. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_ERROR,inRePacketId,inReVerb,networkId);
  179. return true;
  180. }
  181. bool IncomingPacket::_doACK(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  182. {
  183. if (!peer->rateGateACK(RR->node->now()))
  184. return true;
  185. /* Dissect incoming ACK packet. From this we can estimate current throughput of the path, establish known
  186. * maximums and detect packet loss. */
  187. if (peer->localMultipathSupport()) {
  188. int32_t ackedBytes;
  189. if (payloadLength() != sizeof(ackedBytes)) {
  190. return true; // ignore
  191. }
  192. memcpy(&ackedBytes, payload(), sizeof(ackedBytes));
  193. _path->receivedAck(RR->node->now(), Utils::ntoh(ackedBytes));
  194. peer->inferRemoteMultipathEnabled();
  195. }
  196. return true;
  197. }
  198. bool IncomingPacket::_doQOS_MEASUREMENT(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  199. {
  200. if (!peer->rateGateQoS(RR->node->now()))
  201. return true;
  202. /* Dissect incoming QoS packet. From this we can compute latency values and their variance.
  203. * The latency variance is used as a measure of "jitter". */
  204. if (peer->localMultipathSupport()) {
  205. if (payloadLength() > ZT_PATH_MAX_QOS_PACKET_SZ || payloadLength() < ZT_PATH_MIN_QOS_PACKET_SZ) {
  206. return true; // ignore
  207. }
  208. const int64_t now = RR->node->now();
  209. uint64_t rx_id[ZT_PATH_QOS_TABLE_SIZE];
  210. uint16_t rx_ts[ZT_PATH_QOS_TABLE_SIZE];
  211. char *begin = (char *)payload();
  212. char *ptr = begin;
  213. int count = 0;
  214. int len = payloadLength();
  215. // Read packet IDs and latency compensation intervals for each packet tracked by this QoS packet
  216. while (ptr < (begin + len) && (count < ZT_PATH_QOS_TABLE_SIZE)) {
  217. memcpy((void*)&rx_id[count], ptr, sizeof(uint64_t));
  218. ptr+=sizeof(uint64_t);
  219. memcpy((void*)&rx_ts[count], ptr, sizeof(uint16_t));
  220. ptr+=sizeof(uint16_t);
  221. count++;
  222. }
  223. _path->receivedQoS(now, count, rx_id, rx_ts);
  224. peer->inferRemoteMultipathEnabled();
  225. }
  226. return true;
  227. }
  228. bool IncomingPacket::_doHELLO(const RuntimeEnvironment *RR,void *tPtr,const bool alreadyAuthenticated)
  229. {
  230. const int64_t now = RR->node->now();
  231. const uint64_t pid = packetId();
  232. const Address fromAddress(source());
  233. const unsigned int protoVersion = (*this)[ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION];
  234. const unsigned int vMajor = (*this)[ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION];
  235. const unsigned int vMinor = (*this)[ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION];
  236. const unsigned int vRevision = at<uint16_t>(ZT_PROTO_VERB_HELLO_IDX_REVISION);
  237. const int64_t timestamp = at<int64_t>(ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP);
  238. Identity id;
  239. unsigned int ptr = ZT_PROTO_VERB_HELLO_IDX_IDENTITY + id.deserialize(*this,ZT_PROTO_VERB_HELLO_IDX_IDENTITY);
  240. if (protoVersion < ZT_PROTO_VERSION_MIN) {
  241. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"protocol version too old");
  242. return true;
  243. }
  244. if (fromAddress != id.address()) {
  245. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"identity/address mismatch");
  246. return true;
  247. }
  248. SharedPtr<Peer> peer(RR->topology->get(id.address()));
  249. if (peer) {
  250. // We already have an identity with this address -- check for collisions
  251. if (!alreadyAuthenticated) {
  252. if (peer->identity() != id) {
  253. // Identity is different from the one we already have -- address collision
  254. // Check rate limits
  255. if (!RR->node->rateGateIdentityVerification(now,_path->address()))
  256. return true;
  257. uint8_t key[ZT_PEER_SECRET_KEY_LENGTH];
  258. if (RR->identity.agree(id,key)) {
  259. if (dearmor(key)) { // ensure packet is authentic, otherwise drop
  260. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"address collision");
  261. Packet outp(id.address(),RR->identity.address(),Packet::VERB_ERROR);
  262. outp.append((uint8_t)Packet::VERB_HELLO);
  263. outp.append((uint64_t)pid);
  264. outp.append((uint8_t)Packet::ERROR_IDENTITY_COLLISION);
  265. outp.armor(key,true);
  266. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  267. } else {
  268. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,pid,fromAddress,hops(),"invalid MAC");
  269. }
  270. } else {
  271. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,pid,fromAddress,hops(),"invalid identity");
  272. }
  273. return true;
  274. } else {
  275. // Identity is the same as the one we already have -- check packet integrity
  276. if (!dearmor(peer->key())) {
  277. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,pid,fromAddress,hops(),"invalid MAC");
  278. return true;
  279. }
  280. // Continue at // VALID
  281. }
  282. } // else if alreadyAuthenticated then continue at // VALID
  283. } else {
  284. // We don't already have an identity with this address -- validate and learn it
  285. // Sanity check: this basically can't happen
  286. if (alreadyAuthenticated) {
  287. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"illegal alreadyAuthenticated state");
  288. return true;
  289. }
  290. // Check rate limits
  291. if (!RR->node->rateGateIdentityVerification(now,_path->address())) {
  292. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"rate limit exceeded");
  293. return true;
  294. }
  295. // Check packet integrity and MAC (this is faster than locallyValidate() so do it first to filter out total crap)
  296. SharedPtr<Peer> newPeer(new Peer(RR,RR->identity,id));
  297. if (!dearmor(newPeer->key())) {
  298. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,pid,fromAddress,hops(),"invalid MAC");
  299. return true;
  300. }
  301. // Check that identity's address is valid as per the derivation function
  302. if (!id.locallyValidate()) {
  303. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"invalid identity");
  304. return true;
  305. }
  306. peer = RR->topology->add(newPeer);
  307. // Continue at // VALID
  308. }
  309. // VALID -- if we made it here, packet passed identity and authenticity checks!
  310. // Get external surface address if present (was not in old versions)
  311. InetAddress externalSurfaceAddress;
  312. if (ptr < size()) {
  313. ptr += externalSurfaceAddress.deserialize(*this,ptr);
  314. if ((externalSurfaceAddress)&&(hops() == 0))
  315. RR->sa->iam(tPtr,id.address(),_path->localSocket(),_path->address(),externalSurfaceAddress,RR->topology->isRoot(id),now);
  316. }
  317. // Send OK(HELLO) with an echo of the packet's timestamp and some of the same
  318. // information about us: version, sent-to address, etc.
  319. Packet outp(id.address(),RR->identity.address(),Packet::VERB_OK);
  320. outp.append((unsigned char)Packet::VERB_HELLO);
  321. outp.append((uint64_t)pid);
  322. outp.append((uint64_t)timestamp);
  323. outp.append((unsigned char)ZT_PROTO_VERSION);
  324. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  325. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  326. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  327. _path->address().serialize(outp);
  328. outp.armor(peer->key(),true);
  329. _path->send(RR,tPtr,outp.data(),outp.size(),now);
  330. peer->setRemoteVersion(protoVersion,vMajor,vMinor,vRevision); // important for this to go first so received() knows the version
  331. peer->received(tPtr,_path,hops(),pid,payloadLength(),Packet::VERB_HELLO,0,Packet::VERB_NOP,0);
  332. return true;
  333. }
  334. bool IncomingPacket::_doOK(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  335. {
  336. const Packet::Verb inReVerb = (Packet::Verb)(*this)[ZT_PROTO_VERB_OK_IDX_IN_RE_VERB];
  337. const uint64_t inRePacketId = at<uint64_t>(ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID);
  338. uint64_t networkId = 0;
  339. if (!RR->node->expectingReplyTo(inRePacketId))
  340. return true;
  341. switch(inReVerb) {
  342. case Packet::VERB_HELLO: {
  343. const uint64_t latency = RR->node->now() - at<uint64_t>(ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP);
  344. const unsigned int vProto = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION];
  345. const unsigned int vMajor = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION];
  346. const unsigned int vMinor = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION];
  347. const unsigned int vRevision = at<uint16_t>(ZT_PROTO_VERB_HELLO__OK__IDX_REVISION);
  348. if (vProto < ZT_PROTO_VERSION_MIN)
  349. return true;
  350. InetAddress externalSurfaceAddress;
  351. unsigned int ptr = ZT_PROTO_VERB_HELLO__OK__IDX_REVISION + 2;
  352. // Get reported external surface address if present
  353. if (ptr < size())
  354. ptr += externalSurfaceAddress.deserialize(*this,ptr);
  355. if (!hops()) {
  356. _path->updateLatency((unsigned int)latency,RR->node->now());
  357. }
  358. peer->setRemoteVersion(vProto,vMajor,vMinor,vRevision);
  359. if ((externalSurfaceAddress)&&(hops() == 0))
  360. RR->sa->iam(tPtr,peer->address(),_path->localSocket(),_path->address(),externalSurfaceAddress,RR->topology->isRoot(peer->identity()),RR->node->now());
  361. } break;
  362. case Packet::VERB_WHOIS:
  363. if (RR->topology->isRoot(peer->identity())) {
  364. unsigned int p = ZT_PROTO_VERB_WHOIS__OK__IDX_IDENTITY;
  365. while (p < size()) {
  366. try {
  367. Identity id;
  368. p += id.deserialize(*this,p);
  369. if (id)
  370. RR->sw->doAnythingWaitingForPeer(tPtr,RR->topology->add(SharedPtr<Peer>(new Peer(RR,RR->identity,id))));
  371. } catch ( ... ) {
  372. break;
  373. }
  374. }
  375. }
  376. break;
  377. case Packet::VERB_NETWORK_CONFIG_REQUEST: {
  378. networkId = at<uint64_t>(ZT_PROTO_VERB_OK_IDX_PAYLOAD);
  379. const SharedPtr<Network> network(RR->node->network(networkId));
  380. if (network)
  381. network->handleConfigChunk(tPtr,packetId(),source(),*this,ZT_PROTO_VERB_OK_IDX_PAYLOAD);
  382. } break;
  383. case Packet::VERB_MULTICAST_GATHER: {
  384. networkId = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID);
  385. const SharedPtr<Network> network(RR->node->network(networkId));
  386. if (network) {
  387. const MulticastGroup mg(MAC(field(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_MAC,6),6),at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_ADI));
  388. const unsigned int count = at<uint16_t>(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_GATHER_RESULTS + 4);
  389. RR->mc->addMultiple(tPtr,RR->node->now(),networkId,mg,field(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_GATHER_RESULTS + 6,count * 5),count,at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_GATHER_RESULTS));
  390. }
  391. } break;
  392. case Packet::VERB_MULTICAST_FRAME: {
  393. const unsigned int flags = (*this)[ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_FLAGS];
  394. networkId = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_NETWORK_ID);
  395. const MulticastGroup mg(MAC(field(ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_MAC,6),6),at<uint32_t>(ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_ADI));
  396. const SharedPtr<Network> network(RR->node->network(networkId));
  397. if (network) {
  398. unsigned int offset = 0;
  399. if ((flags & 0x01) != 0) { // deprecated but still used by older peers
  400. CertificateOfMembership com;
  401. offset += com.deserialize(*this,ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_COM_AND_GATHER_RESULTS);
  402. if (com)
  403. network->addCredential(tPtr,com);
  404. }
  405. if ((flags & 0x02) != 0) {
  406. // OK(MULTICAST_FRAME) includes implicit gather results
  407. offset += ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_COM_AND_GATHER_RESULTS;
  408. unsigned int totalKnown = at<uint32_t>(offset); offset += 4;
  409. unsigned int count = at<uint16_t>(offset); offset += 2;
  410. RR->mc->addMultiple(tPtr,RR->node->now(),networkId,mg,field(offset,count * 5),count,totalKnown);
  411. }
  412. }
  413. } break;
  414. default: break;
  415. }
  416. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_OK,inRePacketId,inReVerb,networkId);
  417. return true;
  418. }
  419. bool IncomingPacket::_doWHOIS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  420. {
  421. // TODO
  422. //if ((!RR->topology->amUpstream())&&(!peer->rateGateInboundWhoisRequest(RR->node->now())))
  423. // return true;
  424. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  425. outp.append((unsigned char)Packet::VERB_WHOIS);
  426. outp.append(packetId());
  427. unsigned int count = 0;
  428. unsigned int ptr = ZT_PACKET_IDX_PAYLOAD;
  429. while ((ptr + ZT_ADDRESS_LENGTH) <= size()) {
  430. const Address addr(field(ptr,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  431. ptr += ZT_ADDRESS_LENGTH;
  432. const Identity id(RR->topology->getIdentity(tPtr,addr));
  433. if (id) {
  434. id.serialize(outp,false);
  435. ++count;
  436. } else {
  437. // Request unknown WHOIS from upstream from us (if we have one)
  438. RR->sw->requestWhois(tPtr,RR->node->now(),addr);
  439. }
  440. }
  441. if (count > 0) {
  442. outp.armor(peer->key(),true);
  443. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  444. }
  445. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_WHOIS,0,Packet::VERB_NOP,0);
  446. return true;
  447. }
  448. bool IncomingPacket::_doRENDEZVOUS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  449. {
  450. if (RR->topology->isRoot(peer->identity())) {
  451. const Address with(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  452. const SharedPtr<Peer> rendezvousWith(RR->topology->get(with));
  453. if (rendezvousWith) {
  454. const unsigned int port = at<uint16_t>(ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT);
  455. const unsigned int addrlen = (*this)[ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN];
  456. if ((port > 0)&&((addrlen == 4)||(addrlen == 16))) {
  457. InetAddress atAddr(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS,addrlen),addrlen,port);
  458. if (RR->node->shouldUsePathForZeroTierTraffic(tPtr,with,_path->localSocket(),atAddr)) {
  459. const uint64_t junk = RR->node->prng();
  460. RR->node->putPacket(tPtr,_path->localSocket(),atAddr,&junk,4,2); // send low-TTL junk packet to 'open' local NAT(s) and stateful firewalls
  461. rendezvousWith->attemptToContactAt(tPtr,_path->localSocket(),atAddr,RR->node->now(),false);
  462. }
  463. }
  464. }
  465. }
  466. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_RENDEZVOUS,0,Packet::VERB_NOP,0);
  467. return true;
  468. }
  469. bool IncomingPacket::_doFRAME(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  470. {
  471. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID);
  472. const SharedPtr<Network> network(RR->node->network(nwid));
  473. if (network) {
  474. if (network->gate(tPtr,peer)) {
  475. if (size() > ZT_PROTO_VERB_FRAME_IDX_PAYLOAD) {
  476. const unsigned int etherType = at<uint16_t>(ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE);
  477. const MAC sourceMac(peer->address(),nwid);
  478. const unsigned int frameLen = size() - ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  479. const uint8_t *const frameData = reinterpret_cast<const uint8_t *>(data()) + ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  480. if (network->filterIncomingPacket(tPtr,peer,RR->identity.address(),sourceMac,network->mac(),frameData,frameLen,etherType,0) > 0)
  481. RR->node->putFrame(tPtr,nwid,network->userPtr(),sourceMac,network->mac(),etherType,0,(const void *)frameData,frameLen);
  482. }
  483. } else {
  484. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  485. return false;
  486. }
  487. }
  488. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_FRAME,0,Packet::VERB_NOP,nwid);
  489. return true;
  490. }
  491. bool IncomingPacket::_doEXT_FRAME(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  492. {
  493. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID);
  494. const SharedPtr<Network> network(RR->node->network(nwid));
  495. if (network) {
  496. const unsigned int flags = (*this)[ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS];
  497. unsigned int comLen = 0;
  498. if ((flags & 0x01) != 0) { // inline COM with EXT_FRAME is deprecated but still used with old peers
  499. CertificateOfMembership com;
  500. comLen = com.deserialize(*this,ZT_PROTO_VERB_EXT_FRAME_IDX_COM);
  501. if (com)
  502. network->addCredential(tPtr,com);
  503. }
  504. if (!network->gate(tPtr,peer)) {
  505. RR->t->incomingNetworkAccessDenied(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,true);
  506. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  507. return false;
  508. }
  509. if (size() > ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD) {
  510. const unsigned int etherType = at<uint16_t>(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE);
  511. const MAC to(field(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_TO,ZT_PROTO_VERB_EXT_FRAME_LEN_TO),ZT_PROTO_VERB_EXT_FRAME_LEN_TO);
  512. const MAC from(field(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_FROM,ZT_PROTO_VERB_EXT_FRAME_LEN_FROM),ZT_PROTO_VERB_EXT_FRAME_LEN_FROM);
  513. const unsigned int frameLen = size() - (comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD);
  514. const uint8_t *const frameData = (const uint8_t *)field(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD,frameLen);
  515. if ((!from)||(from == network->mac())) {
  516. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,nwid);
  517. return true;
  518. }
  519. switch (network->filterIncomingPacket(tPtr,peer,RR->identity.address(),from,to,frameData,frameLen,etherType,0)) {
  520. case 1:
  521. if (from != MAC(peer->address(),nwid)) {
  522. if (network->config().permitsBridging(peer->address())) {
  523. network->learnBridgeRoute(from,peer->address());
  524. } else {
  525. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,from,to,"bridging not allowed (remote)");
  526. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,nwid);
  527. return true;
  528. }
  529. } else if (to != network->mac()) {
  530. if (to.isMulticast()) {
  531. if (network->config().multicastLimit == 0) {
  532. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,from,to,"multicast disabled");
  533. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,nwid);
  534. return true;
  535. }
  536. } else if (!network->config().permitsBridging(RR->identity.address())) {
  537. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,from,to,"bridging not allowed (local)");
  538. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,nwid);
  539. return true;
  540. }
  541. }
  542. // fall through -- 2 means accept regardless of bridging checks or other restrictions
  543. case 2:
  544. RR->node->putFrame(tPtr,nwid,network->userPtr(),from,to,etherType,0,(const void *)frameData,frameLen);
  545. break;
  546. }
  547. }
  548. if ((flags & 0x10) != 0) { // ACK requested
  549. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  550. outp.append((uint8_t)Packet::VERB_EXT_FRAME);
  551. outp.append((uint64_t)packetId());
  552. outp.append((uint64_t)nwid);
  553. outp.armor(peer->key(),true);
  554. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  555. }
  556. }
  557. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,nwid);
  558. return true;
  559. }
  560. bool IncomingPacket::_doECHO(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  561. {
  562. if (!peer->rateGateEchoRequest(RR->node->now()))
  563. return true;
  564. const uint64_t pid = packetId();
  565. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  566. outp.append((unsigned char)Packet::VERB_ECHO);
  567. outp.append((uint64_t)pid);
  568. if (size() > ZT_PACKET_IDX_PAYLOAD)
  569. outp.append(reinterpret_cast<const unsigned char *>(data()) + ZT_PACKET_IDX_PAYLOAD,size() - ZT_PACKET_IDX_PAYLOAD);
  570. outp.armor(peer->key(),true);
  571. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  572. peer->received(tPtr,_path,hops(),pid,payloadLength(),Packet::VERB_ECHO,0,Packet::VERB_NOP,0);
  573. return true;
  574. }
  575. bool IncomingPacket::_doMULTICAST_LIKE(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  576. {
  577. const int64_t now = RR->node->now();
  578. bool authorized = false;
  579. uint64_t lastNwid = 0;
  580. // Packet contains a series of 18-byte network,MAC,ADI tuples
  581. for(unsigned int ptr=ZT_PACKET_IDX_PAYLOAD;ptr<size();ptr+=18) {
  582. const uint64_t nwid = at<uint64_t>(ptr);
  583. if (nwid != lastNwid) {
  584. lastNwid = nwid;
  585. SharedPtr<Network> network(RR->node->network(nwid));
  586. if (network)
  587. authorized = network->gate(tPtr,peer);
  588. //if (!authorized)
  589. // authorized = ((RR->topology->amUpstream())||(RR->node->localControllerHasAuthorized(now,nwid,peer->address())));
  590. }
  591. if (authorized)
  592. RR->mc->add(tPtr,now,nwid,MulticastGroup(MAC(field(ptr + 8,6),6),at<uint32_t>(ptr + 14)),peer->address());
  593. }
  594. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_MULTICAST_LIKE,0,Packet::VERB_NOP,0);
  595. return true;
  596. }
  597. bool IncomingPacket::_doNETWORK_CREDENTIALS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  598. {
  599. if (!peer->rateGateCredentialsReceived(RR->node->now()))
  600. return true;
  601. CertificateOfMembership com;
  602. Capability cap;
  603. Tag tag;
  604. Revocation revocation;
  605. CertificateOfOwnership coo;
  606. SharedPtr<Network> network;
  607. unsigned int p = ZT_PACKET_IDX_PAYLOAD;
  608. while ((p < size())&&((*this)[p] != 0)) {
  609. p += com.deserialize(*this,p);
  610. if (com) {
  611. network = RR->node->network(com.networkId());
  612. if (network) {
  613. if (network->addCredential(tPtr,com) == Membership::ADD_DEFERRED_FOR_WHOIS)
  614. return false;
  615. }
  616. }
  617. }
  618. ++p; // skip trailing 0 after COMs if present
  619. if (p < size()) { // older ZeroTier versions do not send capabilities, tags, or revocations
  620. const unsigned int numCapabilities = at<uint16_t>(p); p += 2;
  621. for(unsigned int i=0;i<numCapabilities;++i) {
  622. p += cap.deserialize(*this,p);
  623. if ((!network)||(network->id() != cap.networkId()))
  624. network = RR->node->network(cap.networkId());
  625. if (network) {
  626. if (network->addCredential(tPtr,cap) == Membership::ADD_DEFERRED_FOR_WHOIS)
  627. return false;
  628. }
  629. }
  630. if (p >= size()) return true;
  631. const unsigned int numTags = at<uint16_t>(p); p += 2;
  632. for(unsigned int i=0;i<numTags;++i) {
  633. p += tag.deserialize(*this,p);
  634. if ((!network)||(network->id() != tag.networkId()))
  635. network = RR->node->network(tag.networkId());
  636. if (network) {
  637. if (network->addCredential(tPtr,tag) == Membership::ADD_DEFERRED_FOR_WHOIS)
  638. return false;
  639. }
  640. }
  641. if (p >= size()) return true;
  642. const unsigned int numRevocations = at<uint16_t>(p); p += 2;
  643. for(unsigned int i=0;i<numRevocations;++i) {
  644. p += revocation.deserialize(*this,p);
  645. if ((!network)||(network->id() != revocation.networkId()))
  646. network = RR->node->network(revocation.networkId());
  647. if (network) {
  648. if (network->addCredential(tPtr,peer->address(),revocation) == Membership::ADD_DEFERRED_FOR_WHOIS)
  649. return false;
  650. }
  651. }
  652. if (p >= size()) return true;
  653. const unsigned int numCoos = at<uint16_t>(p); p += 2;
  654. for(unsigned int i=0;i<numCoos;++i) {
  655. p += coo.deserialize(*this,p);
  656. if ((!network)||(network->id() != coo.networkId()))
  657. network = RR->node->network(coo.networkId());
  658. if (network) {
  659. if (network->addCredential(tPtr,coo) == Membership::ADD_DEFERRED_FOR_WHOIS)
  660. return false;
  661. }
  662. }
  663. }
  664. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_NETWORK_CREDENTIALS,0,Packet::VERB_NOP,(network) ? network->id() : 0);
  665. return true;
  666. }
  667. bool IncomingPacket::_doNETWORK_CONFIG_REQUEST(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  668. {
  669. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID);
  670. const unsigned int hopCount = hops();
  671. const uint64_t requestPacketId = packetId();
  672. if (RR->localNetworkController) {
  673. const unsigned int metaDataLength = (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN <= size()) ? at<uint16_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN) : 0;
  674. const char *metaDataBytes = (metaDataLength != 0) ? (const char *)field(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT,metaDataLength) : (const char *)0;
  675. const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> metaData(metaDataBytes,metaDataLength);
  676. RR->localNetworkController->request(nwid,(hopCount > 0) ? InetAddress() : _path->address(),requestPacketId,peer->identity(),metaData);
  677. } else {
  678. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_ERROR);
  679. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  680. outp.append(requestPacketId);
  681. outp.append((unsigned char)Packet::ERROR_UNSUPPORTED_OPERATION);
  682. outp.append(nwid);
  683. outp.armor(peer->key(),true);
  684. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  685. }
  686. peer->received(tPtr,_path,hopCount,requestPacketId,payloadLength(),Packet::VERB_NETWORK_CONFIG_REQUEST,0,Packet::VERB_NOP,nwid);
  687. return true;
  688. }
  689. bool IncomingPacket::_doNETWORK_CONFIG(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  690. {
  691. const SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PACKET_IDX_PAYLOAD)));
  692. if (network) {
  693. const uint64_t configUpdateId = network->handleConfigChunk(tPtr,packetId(),source(),*this,ZT_PACKET_IDX_PAYLOAD);
  694. if (configUpdateId) {
  695. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  696. outp.append((uint8_t)Packet::VERB_ECHO);
  697. outp.append((uint64_t)packetId());
  698. outp.append((uint64_t)network->id());
  699. outp.append((uint64_t)configUpdateId);
  700. outp.armor(peer->key(),true);
  701. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  702. }
  703. }
  704. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_NETWORK_CONFIG,0,Packet::VERB_NOP,(network) ? network->id() : 0);
  705. return true;
  706. }
  707. bool IncomingPacket::_doMULTICAST_GATHER(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  708. {
  709. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID);
  710. const unsigned int flags = (*this)[ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS];
  711. const MulticastGroup mg(MAC(field(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC,6),6),at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI));
  712. const unsigned int gatherLimit = at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_GATHER_LIMIT);
  713. const SharedPtr<Network> network(RR->node->network(nwid));
  714. if ((flags & 0x01) != 0) {
  715. try {
  716. CertificateOfMembership com;
  717. com.deserialize(*this,ZT_PROTO_VERB_MULTICAST_GATHER_IDX_COM);
  718. if ((com)&&(network))
  719. network->addCredential(tPtr,com);
  720. } catch ( ... ) {} // discard invalid COMs
  721. }
  722. if (network) {
  723. if (!network->gate(tPtr,peer)) {
  724. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  725. return false;
  726. }
  727. }
  728. const int64_t now = RR->node->now();
  729. if (gatherLimit) {
  730. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  731. outp.append((unsigned char)Packet::VERB_MULTICAST_GATHER);
  732. outp.append(packetId());
  733. outp.append(nwid);
  734. mg.mac().appendTo(outp);
  735. outp.append((uint32_t)mg.adi());
  736. const unsigned int gatheredLocally = RR->mc->gather(peer->address(),nwid,mg,outp,gatherLimit);
  737. if (gatheredLocally > 0) {
  738. outp.armor(peer->key(),true);
  739. _path->send(RR,tPtr,outp.data(),outp.size(),now);
  740. }
  741. }
  742. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_MULTICAST_GATHER,0,Packet::VERB_NOP,nwid);
  743. return true;
  744. }
  745. bool IncomingPacket::_doMULTICAST_FRAME(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  746. {
  747. unsigned int offset = ZT_PACKET_IDX_PAYLOAD;
  748. const uint64_t nwid = at<uint64_t>(offset); offset += 8;
  749. const unsigned int flags = (*this)[offset]; ++offset;
  750. const SharedPtr<Network> network(RR->node->network(nwid));
  751. if (network) {
  752. if ((flags & 0x01) != 0) {
  753. // This is deprecated but may still be sent by old peers
  754. CertificateOfMembership com;
  755. offset += com.deserialize(*this,offset);
  756. if (com)
  757. network->addCredential(tPtr,com);
  758. }
  759. if (!network->gate(tPtr,peer)) {
  760. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  761. return false;
  762. }
  763. unsigned int gatherLimit = 0;
  764. if ((flags & 0x02) != 0) {
  765. gatherLimit = at<uint32_t>(offset); offset += 4;
  766. }
  767. MAC from;
  768. if ((flags & 0x04) != 0) {
  769. from.setTo(field(offset,6),6); offset += 6;
  770. } else {
  771. from.fromAddress(peer->address(),nwid);
  772. }
  773. const unsigned int recipientsOffset = offset;
  774. std::list<Address> recipients;
  775. if ((flags & 0x08) != 0) {
  776. const unsigned int rc = at<uint16_t>(offset); offset += 2;
  777. for(unsigned int i=0;i<rc;++i) {
  778. const Address a(field(offset,5),5);
  779. if ((a != peer->address())&&(a != RR->identity.address())) {
  780. recipients.push_back(a);
  781. }
  782. offset += 5;
  783. }
  784. }
  785. const unsigned int afterRecipientsOffset = offset;
  786. const MulticastGroup to(MAC(field(offset,6),6),at<uint32_t>(offset + 6)); offset += 10;
  787. const unsigned int etherType = at<uint16_t>(offset); offset += 2;
  788. const unsigned int frameLen = size() - offset;
  789. if (network->config().multicastLimit == 0) {
  790. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_MULTICAST_FRAME,from,to.mac(),"multicast disabled");
  791. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,nwid);
  792. return true;
  793. }
  794. if (!to.mac().isMulticast()) {
  795. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),source(),hops(),Packet::VERB_MULTICAST_FRAME,"destination not multicast");
  796. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,nwid);
  797. return true;
  798. }
  799. if ((!from)||(from.isMulticast())||(from == network->mac())) {
  800. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),source(),hops(),Packet::VERB_MULTICAST_FRAME,"invalid source MAC");
  801. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,nwid);
  802. return true;
  803. }
  804. if ((frameLen > 0)&&(frameLen <= ZT_MAX_MTU)) {
  805. const uint8_t *const frameData = ((const uint8_t *)unsafeData()) + offset;
  806. if (network->filterIncomingPacket(tPtr,peer,RR->identity.address(),from,to.mac(),frameData,frameLen,etherType,0) > 0) {
  807. RR->node->putFrame(tPtr,nwid,network->userPtr(),from,to.mac(),etherType,0,(const void *)frameData,frameLen);
  808. }
  809. }
  810. if (!recipients.empty()) {
  811. const std::vector<Address> anchors = network->config().anchors();
  812. const bool amAnchor = (std::find(anchors.begin(),anchors.end(),RR->identity.address()) != anchors.end());
  813. for(std::list<Address>::iterator ra(recipients.begin());ra!=recipients.end();) {
  814. SharedPtr<Peer> recipient(RR->topology->get(*ra));
  815. if ((recipient)&&((recipient->remoteVersionProtocol() < 10)||(amAnchor))) {
  816. Packet outp(*ra,RR->identity.address(),Packet::VERB_MULTICAST_FRAME);
  817. outp.append(field(ZT_PACKET_IDX_PAYLOAD,recipientsOffset - ZT_PACKET_IDX_PAYLOAD),recipientsOffset - ZT_PACKET_IDX_PAYLOAD);
  818. outp.append(field(afterRecipientsOffset,size() - afterRecipientsOffset),size() - afterRecipientsOffset);
  819. RR->sw->send(tPtr,outp,true);
  820. recipients.erase(ra++);
  821. } else ++ra;
  822. }
  823. if (!recipients.empty()) {
  824. Packet outp(recipients.front(),RR->identity.address(),Packet::VERB_MULTICAST_FRAME);
  825. recipients.pop_front();
  826. outp.append(field(ZT_PACKET_IDX_PAYLOAD,recipientsOffset - ZT_PACKET_IDX_PAYLOAD),recipientsOffset - ZT_PACKET_IDX_PAYLOAD);
  827. if (!recipients.empty()) {
  828. outp.append((uint16_t)recipients.size());
  829. for(std::list<Address>::iterator ra(recipients.begin());ra!=recipients.end();++ra)
  830. ra->appendTo(outp);
  831. }
  832. outp.append(field(afterRecipientsOffset,size() - afterRecipientsOffset),size() - afterRecipientsOffset);
  833. RR->sw->send(tPtr,outp,true);
  834. }
  835. }
  836. if (gatherLimit) { // DEPRECATED but still supported
  837. Packet outp(source(),RR->identity.address(),Packet::VERB_OK);
  838. outp.append((unsigned char)Packet::VERB_MULTICAST_FRAME);
  839. outp.append(packetId());
  840. outp.append(nwid);
  841. to.mac().appendTo(outp);
  842. outp.append((uint32_t)to.adi());
  843. outp.append((unsigned char)0x02); // flag 0x02 = contains gather results
  844. if (RR->mc->gather(peer->address(),nwid,to,outp,gatherLimit)) {
  845. outp.armor(peer->key(),true);
  846. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  847. }
  848. }
  849. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,nwid);
  850. return true;
  851. } else {
  852. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  853. return false;
  854. }
  855. }
  856. bool IncomingPacket::_doPUSH_DIRECT_PATHS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  857. {
  858. const int64_t now = RR->node->now();
  859. // First, subject this to a rate limit
  860. if (!peer->rateGatePushDirectPaths(now)) {
  861. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_PUSH_DIRECT_PATHS,0,Packet::VERB_NOP,0);
  862. return true;
  863. }
  864. // Second, limit addresses by scope and type
  865. uint8_t countPerScope[ZT_INETADDRESS_MAX_SCOPE+1][2]; // [][0] is v4, [][1] is v6
  866. memset(countPerScope,0,sizeof(countPerScope));
  867. unsigned int count = at<uint16_t>(ZT_PACKET_IDX_PAYLOAD);
  868. unsigned int ptr = ZT_PACKET_IDX_PAYLOAD + 2;
  869. while (count--) { // if ptr overflows Buffer will throw
  870. // TODO: some flags are not yet implemented
  871. unsigned int flags = (*this)[ptr++];
  872. unsigned int extLen = at<uint16_t>(ptr); ptr += 2;
  873. ptr += extLen; // unused right now
  874. unsigned int addrType = (*this)[ptr++];
  875. unsigned int addrLen = (*this)[ptr++];
  876. switch(addrType) {
  877. case 4: {
  878. const InetAddress a(field(ptr,4),4,at<uint16_t>(ptr + 4));
  879. if ((!( ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT) == 0) && (peer->hasActivePathTo(now,a)) )) && // not already known
  880. (RR->node->shouldUsePathForZeroTierTraffic(tPtr,peer->address(),_path->localSocket(),a)) ) // should use path
  881. {
  882. if ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT) != 0) {
  883. peer->clusterRedirect(tPtr,_path,a,now);
  884. } else if (++countPerScope[(int)a.ipScope()][0] <= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY) {
  885. peer->attemptToContactAt(tPtr,InetAddress(),a,now,false);
  886. }
  887. }
  888. } break;
  889. case 6: {
  890. const InetAddress a(field(ptr,16),16,at<uint16_t>(ptr + 16));
  891. if ((!( ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT) == 0) && (peer->hasActivePathTo(now,a)) )) && // not already known
  892. (RR->node->shouldUsePathForZeroTierTraffic(tPtr,peer->address(),_path->localSocket(),a)) ) // should use path
  893. {
  894. if ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT) != 0) {
  895. peer->clusterRedirect(tPtr,_path,a,now);
  896. } else if (++countPerScope[(int)a.ipScope()][1] <= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY) {
  897. peer->attemptToContactAt(tPtr,InetAddress(),a,now,false);
  898. }
  899. }
  900. } break;
  901. }
  902. ptr += addrLen;
  903. }
  904. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_PUSH_DIRECT_PATHS,0,Packet::VERB_NOP,0);
  905. return true;
  906. }
  907. bool IncomingPacket::_doUSER_MESSAGE(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  908. {
  909. if (likely(size() >= (ZT_PACKET_IDX_PAYLOAD + 8))) {
  910. ZT_UserMessage um;
  911. um.origin = peer->address().toInt();
  912. um.typeId = at<uint64_t>(ZT_PACKET_IDX_PAYLOAD);
  913. um.data = reinterpret_cast<const void *>(reinterpret_cast<const uint8_t *>(data()) + ZT_PACKET_IDX_PAYLOAD + 8);
  914. um.length = size() - (ZT_PACKET_IDX_PAYLOAD + 8);
  915. RR->node->postEvent(tPtr,ZT_EVENT_USER_MESSAGE,reinterpret_cast<const void *>(&um));
  916. }
  917. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_USER_MESSAGE,0,Packet::VERB_NOP,0);
  918. return true;
  919. }
  920. bool IncomingPacket::_doREMOTE_TRACE(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  921. {
  922. ZT_RemoteTrace rt;
  923. const char *ptr = reinterpret_cast<const char *>(data()) + ZT_PACKET_IDX_PAYLOAD;
  924. const char *const eof = reinterpret_cast<const char *>(data()) + size();
  925. rt.origin = peer->address().toInt();
  926. rt.data = const_cast<char *>(ptr); // start of first string
  927. while (ptr < eof) {
  928. if (!*ptr) { // end of string
  929. rt.len = (unsigned int)(ptr - rt.data);
  930. if ((rt.len > 0)&&(rt.len <= ZT_MAX_REMOTE_TRACE_SIZE)) {
  931. RR->node->postEvent(tPtr,ZT_EVENT_REMOTE_TRACE,&rt);
  932. }
  933. rt.data = const_cast<char *>(++ptr); // start of next string, if any
  934. } else {
  935. ++ptr;
  936. }
  937. }
  938. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_REMOTE_TRACE,0,Packet::VERB_NOP,0);
  939. return true;
  940. }
  941. void IncomingPacket::_sendErrorNeedCredentials(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer,const uint64_t nwid)
  942. {
  943. Packet outp(source(),RR->identity.address(),Packet::VERB_ERROR);
  944. outp.append((uint8_t)verb());
  945. outp.append(packetId());
  946. outp.append((uint8_t)Packet::ERROR_NEED_MEMBERSHIP_CERTIFICATE);
  947. outp.append(nwid);
  948. outp.armor(peer->key(),true);
  949. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  950. }
  951. } // namespace ZeroTier