IncomingPacket.cpp 43 KB

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