IncomingPacket.cpp 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2025-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include <stdio.h>
  14. #include <string.h>
  15. #include <stdlib.h>
  16. #include "../version.h"
  17. #include "../include/ZeroTierOne.h"
  18. #include "Constants.hpp"
  19. #include "RuntimeEnvironment.hpp"
  20. #include "IncomingPacket.hpp"
  21. #include "Topology.hpp"
  22. #include "Switch.hpp"
  23. #include "Peer.hpp"
  24. #include "NetworkController.hpp"
  25. #include "SelfAwareness.hpp"
  26. #include "Salsa20.hpp"
  27. #include "SHA512.hpp"
  28. #include "World.hpp"
  29. #include "Node.hpp"
  30. #include "CertificateOfMembership.hpp"
  31. #include "Capability.hpp"
  32. #include "Tag.hpp"
  33. #include "Revocation.hpp"
  34. #include "Trace.hpp"
  35. #include "Path.hpp"
  36. #include "Bond.hpp"
  37. namespace ZeroTier {
  38. bool IncomingPacket::tryDecode(const RuntimeEnvironment *RR,void *tPtr,int32_t flowId)
  39. {
  40. const Address sourceAddress(source());
  41. try {
  42. // Check for trusted paths or unencrypted HELLOs (HELLO is the only packet sent in the clear)
  43. const unsigned int c = cipher();
  44. if (c == ZT_PROTO_CIPHER_SUITE__NO_CRYPTO_TRUSTED_PATH) {
  45. // If this is marked as a packet via a trusted path, check source address and path ID.
  46. // Obviously if no trusted paths are configured this always returns false and such
  47. // packets are dropped on the floor.
  48. const uint64_t tpid = trustedPathId();
  49. if (RR->topology->shouldInboundPathBeTrusted(_path->address(),tpid)) {
  50. _authenticated = true;
  51. } else {
  52. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,packetId(),sourceAddress,hops(),"path not trusted");
  53. return true;
  54. }
  55. } else if ((c == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE)&&(verb() == Packet::VERB_HELLO)) {
  56. // Only HELLO is allowed in the clear, but will still have a MAC
  57. return _doHELLO(RR,tPtr,false);
  58. }
  59. const SharedPtr<Peer> peer(RR->topology->getPeer(tPtr,sourceAddress));
  60. if (peer) {
  61. if (!_authenticated) {
  62. if (!dearmor(peer->key(), peer->aesKeys())) {
  63. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,packetId(),sourceAddress,hops(),"invalid MAC");
  64. peer->recordIncomingInvalidPacket(_path);
  65. return true;
  66. }
  67. }
  68. if (!uncompress()) {
  69. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),sourceAddress,hops(),Packet::VERB_NOP,"LZ4 decompression failed");
  70. return true;
  71. }
  72. _authenticated = true;
  73. const Packet::Verb v = verb();
  74. bool r = true;
  75. switch(v) {
  76. //case Packet::VERB_NOP:
  77. default: // ignore unknown verbs, but if they pass auth check they are "received"
  78. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),v,0,Packet::VERB_NOP,false,0,ZT_QOS_NO_FLOW);
  79. break;
  80. case Packet::VERB_HELLO: r = _doHELLO(RR,tPtr,true); break;
  81. case Packet::VERB_QOS_MEASUREMENT: r = _doQOS_MEASUREMENT(RR,tPtr,peer); break;
  82. case Packet::VERB_ERROR: r = _doERROR(RR,tPtr,peer); break;
  83. case Packet::VERB_OK: r = _doOK(RR,tPtr,peer); break;
  84. case Packet::VERB_WHOIS: r = _doWHOIS(RR,tPtr,peer); break;
  85. case Packet::VERB_RENDEZVOUS: r = _doRENDEZVOUS(RR,tPtr,peer); break;
  86. case Packet::VERB_FRAME: r = _doFRAME(RR,tPtr,peer,flowId); break;
  87. case Packet::VERB_EXT_FRAME: r = _doEXT_FRAME(RR,tPtr,peer,flowId); break;
  88. case Packet::VERB_ECHO: r = _doECHO(RR,tPtr,peer); break;
  89. case Packet::VERB_MULTICAST_LIKE: r = _doMULTICAST_LIKE(RR,tPtr,peer); break;
  90. case Packet::VERB_NETWORK_CREDENTIALS: r = _doNETWORK_CREDENTIALS(RR,tPtr,peer); break;
  91. case Packet::VERB_NETWORK_CONFIG_REQUEST: r = _doNETWORK_CONFIG_REQUEST(RR,tPtr,peer); break;
  92. case Packet::VERB_NETWORK_CONFIG: r = _doNETWORK_CONFIG(RR,tPtr,peer); break;
  93. case Packet::VERB_MULTICAST_GATHER: r = _doMULTICAST_GATHER(RR,tPtr,peer); break;
  94. case Packet::VERB_MULTICAST_FRAME: r = _doMULTICAST_FRAME(RR,tPtr,peer); break;
  95. case Packet::VERB_PUSH_DIRECT_PATHS: r = _doPUSH_DIRECT_PATHS(RR,tPtr,peer); break;
  96. case Packet::VERB_USER_MESSAGE: r = _doUSER_MESSAGE(RR,tPtr,peer); break;
  97. case Packet::VERB_REMOTE_TRACE: r = _doREMOTE_TRACE(RR,tPtr,peer); break;
  98. case Packet::VERB_PATH_NEGOTIATION_REQUEST: r = _doPATH_NEGOTIATION_REQUEST(RR,tPtr,peer); break;
  99. }
  100. if (r) {
  101. RR->node->statsLogVerb((unsigned int)v,(unsigned int)size());
  102. return true;
  103. }
  104. return false;
  105. } else {
  106. RR->sw->requestWhois(tPtr,RR->node->now(),sourceAddress);
  107. return false;
  108. }
  109. } catch ( ... ) {
  110. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),sourceAddress,hops(),verb(),"unexpected exception in tryDecode()");
  111. return true;
  112. }
  113. }
  114. bool IncomingPacket::_doERROR(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  115. {
  116. const Packet::Verb inReVerb = (Packet::Verb)(*this)[ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB];
  117. const uint64_t inRePacketId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID);
  118. const Packet::ErrorCode errorCode = (Packet::ErrorCode)(*this)[ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE];
  119. uint64_t networkId = 0;
  120. /* Security note: we do not gate doERROR() with expectingReplyTo() to
  121. * avoid having to log every outgoing packet ID. Instead we put the
  122. * logic to determine whether we should consider an ERROR in each
  123. * error handler. In most cases these are only trusted in specific
  124. * circumstances. */
  125. switch(errorCode) {
  126. case Packet::ERROR_OBJ_NOT_FOUND:
  127. // Object not found, currently only meaningful from network controllers.
  128. if (inReVerb == Packet::VERB_NETWORK_CONFIG_REQUEST) {
  129. const SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)));
  130. if ((network)&&(network->controller() == peer->address()))
  131. network->setNotFound(tPtr);
  132. }
  133. break;
  134. case Packet::ERROR_UNSUPPORTED_OPERATION:
  135. // This can be sent in response to any operation, though right now we only
  136. // consider it meaningful from network controllers. This would indicate
  137. // that the queried node does not support acting as a controller.
  138. if (inReVerb == Packet::VERB_NETWORK_CONFIG_REQUEST) {
  139. const SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)));
  140. if ((network)&&(network->controller() == peer->address()))
  141. network->setNotFound(tPtr);
  142. }
  143. break;
  144. case Packet::ERROR_IDENTITY_COLLISION:
  145. // FIXME: for federation this will need a payload with a signature or something.
  146. if (RR->topology->isUpstream(peer->identity()))
  147. RR->node->postEvent(tPtr,ZT_EVENT_FATAL_ERROR_IDENTITY_COLLISION);
  148. break;
  149. case Packet::ERROR_NEED_MEMBERSHIP_CERTIFICATE: {
  150. // Peers can send this in response to frames if they do not have a recent enough COM from us
  151. networkId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD);
  152. const SharedPtr<Network> network(RR->node->network(networkId));
  153. const int64_t now = RR->node->now();
  154. if ((network)&&(network->config().com))
  155. network->peerRequestedCredentials(tPtr,peer->address(),now);
  156. } break;
  157. case Packet::ERROR_NETWORK_ACCESS_DENIED_: {
  158. // Network controller: network access denied.
  159. const SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)));
  160. if ((network)&&(network->controller() == peer->address()))
  161. network->setAccessDenied(tPtr);
  162. } break;
  163. case Packet::ERROR_UNWANTED_MULTICAST: {
  164. // Members of networks can use this error to indicate that they no longer
  165. // want to receive multicasts on a given channel.
  166. networkId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD);
  167. const SharedPtr<Network> network(RR->node->network(networkId));
  168. if ((network)&&(network->gate(tPtr,peer))) {
  169. const MulticastGroup mg(MAC(field(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD + 8,6),6),at<uint32_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD + 14));
  170. RR->mc->remove(network->id(),mg,peer->address());
  171. }
  172. } break;
  173. case Packet::ERROR_NETWORK_AUTHENTICATION_REQUIRED: {
  174. //fprintf(stderr, "\nPacket::ERROR_NETWORK_AUTHENTICATION_REQUIRED\n\n");
  175. const SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)));
  176. if ((network)&&(network->controller() == peer->address())) {
  177. int s = (int)size() - (ZT_PROTO_VERB_ERROR_IDX_PAYLOAD + 8);
  178. if (s > 2) {
  179. const uint16_t errorDataSize = at<uint16_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD + 8);
  180. s -= 2;
  181. if (s >= (int)errorDataSize) {
  182. Dictionary<8192> authInfo(((const char *)this->data()) + (ZT_PROTO_VERB_ERROR_IDX_PAYLOAD + 10), errorDataSize);
  183. uint64_t authVer = authInfo.getUI(ZT_AUTHINFO_DICT_KEY_VERSION, 0ULL);
  184. if (authVer == 0) {
  185. char authenticationURL[2048];
  186. if (authInfo.get(ZT_AUTHINFO_DICT_KEY_AUTHENTICATION_URL, authenticationURL, sizeof(authenticationURL)) > 0) {
  187. authenticationURL[sizeof(authenticationURL) - 1] = 0; // ensure always zero terminated
  188. network->setAuthenticationRequired(tPtr, authenticationURL);
  189. }
  190. } else if (authVer == 1) {
  191. char issuerURL[2048] = { 0 };
  192. char centralAuthURL[2048] = { 0 };
  193. char ssoNonce[64] = { 0 };
  194. char ssoState[128] = {0};
  195. char ssoClientID[256] = { 0 };
  196. if (authInfo.get(ZT_AUTHINFO_DICT_KEY_ISSUER_URL, issuerURL, sizeof(issuerURL)) > 0) {
  197. issuerURL[sizeof(issuerURL) - 1] = 0;
  198. }
  199. if (authInfo.get(ZT_AUTHINFO_DICT_KEY_CENTRAL_ENDPOINT_URL, centralAuthURL, sizeof(centralAuthURL))>0) {
  200. centralAuthURL[sizeof(centralAuthURL) - 1] = 0;
  201. }
  202. if (authInfo.get(ZT_AUTHINFO_DICT_KEY_NONCE, ssoNonce, sizeof(ssoNonce)) > 0) {
  203. ssoNonce[sizeof(ssoNonce) - 1] = 0;
  204. }
  205. if (authInfo.get(ZT_AUTHINFO_DICT_KEY_STATE, ssoState, sizeof(ssoState)) > 0) {
  206. ssoState[sizeof(ssoState) - 1] = 0;
  207. }
  208. if (authInfo.get(ZT_AUTHINFO_DICT_KEY_CLIENT_ID, ssoClientID, sizeof(ssoClientID)) > 0) {
  209. ssoClientID[sizeof(ssoClientID) - 1] = 0;
  210. }
  211. network->setAuthenticationRequired(tPtr, issuerURL, centralAuthURL, ssoClientID, ssoNonce, ssoState);
  212. }
  213. }
  214. } else {
  215. network->setAuthenticationRequired(tPtr, "");
  216. }
  217. }
  218. } break;
  219. default: break;
  220. }
  221. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_ERROR,inRePacketId,inReVerb,false,networkId,ZT_QOS_NO_FLOW);
  222. return true;
  223. }
  224. bool IncomingPacket::_doQOS_MEASUREMENT(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  225. {
  226. SharedPtr<Bond> bond = peer->bond();
  227. if (!bond || !bond->rateGateQoS(RR->node->now(), _path)) {
  228. return true;
  229. }
  230. if (payloadLength() > ZT_QOS_MAX_PACKET_SIZE || payloadLength() < ZT_QOS_MIN_PACKET_SIZE) {
  231. return true; // ignore
  232. }
  233. const int64_t now = RR->node->now();
  234. uint64_t rx_id[ZT_QOS_TABLE_SIZE];
  235. uint16_t rx_ts[ZT_QOS_TABLE_SIZE];
  236. char *begin = (char *)payload();
  237. char *ptr = begin;
  238. int count = 0;
  239. unsigned int len = payloadLength();
  240. // Read packet IDs and latency compensation intervals for each packet tracked by this QoS packet
  241. while (ptr < (begin + len) && (count < ZT_QOS_TABLE_SIZE)) {
  242. memcpy((void*)&rx_id[count], ptr, sizeof(uint64_t));
  243. ptr+=sizeof(uint64_t);
  244. memcpy((void*)&rx_ts[count], ptr, sizeof(uint16_t));
  245. ptr+=sizeof(uint16_t);
  246. count++;
  247. }
  248. if (bond) {
  249. bond->receivedQoS(_path, now, count, rx_id, rx_ts);
  250. }
  251. return true;
  252. }
  253. bool IncomingPacket::_doHELLO(const RuntimeEnvironment *RR,void *tPtr,const bool alreadyAuthenticated)
  254. {
  255. const int64_t now = RR->node->now();
  256. const uint64_t pid = packetId();
  257. const Address fromAddress(source());
  258. const unsigned int protoVersion = (*this)[ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION];
  259. const unsigned int vMajor = (*this)[ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION];
  260. const unsigned int vMinor = (*this)[ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION];
  261. const unsigned int vRevision = at<uint16_t>(ZT_PROTO_VERB_HELLO_IDX_REVISION);
  262. const int64_t timestamp = at<int64_t>(ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP);
  263. Identity id;
  264. unsigned int ptr = ZT_PROTO_VERB_HELLO_IDX_IDENTITY + id.deserialize(*this,ZT_PROTO_VERB_HELLO_IDX_IDENTITY);
  265. if (protoVersion < ZT_PROTO_VERSION_MIN) {
  266. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"protocol version too old");
  267. return true;
  268. }
  269. if (fromAddress != id.address()) {
  270. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"identity/address mismatch");
  271. return true;
  272. }
  273. SharedPtr<Peer> peer(RR->topology->getPeer(tPtr,id.address()));
  274. if (peer) {
  275. // We already have an identity with this address -- check for collisions
  276. if (!alreadyAuthenticated) {
  277. if (peer->identity() != id) {
  278. // Identity is different from the one we already have -- address collision
  279. // Check rate limits
  280. if (!RR->node->rateGateIdentityVerification(now,_path->address()))
  281. return true;
  282. uint8_t key[ZT_SYMMETRIC_KEY_SIZE];
  283. if (RR->identity.agree(id,key)) {
  284. if (dearmor(key, peer->aesKeysIfSupported())) { // ensure packet is authentic, otherwise drop
  285. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"address collision");
  286. Packet outp(id.address(),RR->identity.address(),Packet::VERB_ERROR);
  287. outp.append((uint8_t)Packet::VERB_HELLO);
  288. outp.append((uint64_t)pid);
  289. outp.append((uint8_t)Packet::ERROR_IDENTITY_COLLISION);
  290. outp.armor(key,true,peer->aesKeysIfSupported());
  291. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  292. } else {
  293. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,pid,fromAddress,hops(),"invalid MAC");
  294. }
  295. } else {
  296. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,pid,fromAddress,hops(),"invalid identity");
  297. }
  298. return true;
  299. } else {
  300. // Identity is the same as the one we already have -- check packet integrity
  301. if (!dearmor(peer->key(), peer->aesKeysIfSupported())) {
  302. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,pid,fromAddress,hops(),"invalid MAC");
  303. return true;
  304. }
  305. // Continue at // VALID
  306. }
  307. } // else if alreadyAuthenticated then continue at // VALID
  308. } else {
  309. // We don't already have an identity with this address -- validate and learn it
  310. // Sanity check: this basically can't happen
  311. if (alreadyAuthenticated) {
  312. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"illegal alreadyAuthenticated state");
  313. return true;
  314. }
  315. // Check rate limits
  316. if (!RR->node->rateGateIdentityVerification(now,_path->address())) {
  317. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"rate limit exceeded");
  318. return true;
  319. }
  320. // Check packet integrity and MAC (this is faster than locallyValidate() so do it first to filter out total crap)
  321. SharedPtr<Peer> newPeer(new Peer(RR,RR->identity,id));
  322. if (!dearmor(newPeer->key(), newPeer->aesKeysIfSupported())) {
  323. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,pid,fromAddress,hops(),"invalid MAC");
  324. return true;
  325. }
  326. // Check that identity's address is valid as per the derivation function
  327. if (!id.locallyValidate()) {
  328. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"invalid identity");
  329. return true;
  330. }
  331. peer = RR->topology->addPeer(tPtr,newPeer);
  332. // Continue at // VALID
  333. }
  334. // VALID -- if we made it here, packet passed identity and authenticity checks!
  335. // Get external surface address if present (was not in old versions)
  336. InetAddress externalSurfaceAddress;
  337. if (ptr < size()) {
  338. ptr += externalSurfaceAddress.deserialize(*this,ptr);
  339. if ((externalSurfaceAddress)&&(hops() == 0))
  340. RR->sa->iam(tPtr,id.address(),_path->localSocket(),_path->address(),externalSurfaceAddress,RR->topology->isUpstream(id),now);
  341. }
  342. // Get primary planet world ID and world timestamp if present
  343. uint64_t planetWorldId = 0;
  344. uint64_t planetWorldTimestamp = 0;
  345. if ((ptr + 16) <= size()) {
  346. planetWorldId = at<uint64_t>(ptr); ptr += 8;
  347. planetWorldTimestamp = at<uint64_t>(ptr); ptr += 8;
  348. }
  349. std::vector< std::pair<uint64_t,uint64_t> > moonIdsAndTimestamps;
  350. if (ptr < size()) {
  351. // Remainder of packet, if present, is encrypted
  352. cryptField(peer->key(),ptr,size() - ptr);
  353. // Get moon IDs and timestamps if present
  354. if ((ptr + 2) <= size()) {
  355. const unsigned int numMoons = at<uint16_t>(ptr); ptr += 2;
  356. for(unsigned int i=0;i<numMoons;++i) {
  357. if ((World::Type)(*this)[ptr++] == World::TYPE_MOON)
  358. moonIdsAndTimestamps.push_back(std::pair<uint64_t,uint64_t>(at<uint64_t>(ptr),at<uint64_t>(ptr + 8)));
  359. ptr += 16;
  360. }
  361. }
  362. }
  363. // Send OK(HELLO) with an echo of the packet's timestamp and some of the same
  364. // information about us: version, sent-to address, etc.
  365. Packet outp(id.address(),RR->identity.address(),Packet::VERB_OK);
  366. outp.append((unsigned char)Packet::VERB_HELLO);
  367. outp.append((uint64_t)pid);
  368. outp.append((uint64_t)timestamp);
  369. outp.append((unsigned char)ZT_PROTO_VERSION);
  370. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  371. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  372. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  373. if (protoVersion >= 5) {
  374. _path->address().serialize(outp);
  375. } else {
  376. /* LEGACY COMPATIBILITY HACK:
  377. *
  378. * For a while now (since 1.0.3), ZeroTier has recognized changes in
  379. * its network environment empirically by examining its external network
  380. * address as reported by trusted peers. In versions prior to 1.1.0
  381. * (protocol version < 5), they did this by saving a snapshot of this
  382. * information (in SelfAwareness.hpp) keyed by reporting device ID and
  383. * address type.
  384. *
  385. * This causes problems when clustering is combined with symmetric NAT.
  386. * Symmetric NAT remaps ports, so different endpoints in a cluster will
  387. * report back different exterior addresses. Since the old code keys
  388. * this by device ID and not sending physical address and compares the
  389. * entire address including port, it constantly thinks its external
  390. * surface is changing and resets connections when talking to a cluster.
  391. *
  392. * In new code we key by sending physical address and device and we also
  393. * take the more conservative position of only interpreting changes in
  394. * IP address (neglecting port) as a change in network topology that
  395. * necessitates a reset. But we can make older clients work here by
  396. * nulling out the port field. Since this info is only used for empirical
  397. * detection of link changes, it doesn't break anything else.
  398. */
  399. InetAddress tmpa(_path->address());
  400. tmpa.setPort(0);
  401. tmpa.serialize(outp);
  402. }
  403. const unsigned int worldUpdateSizeAt = outp.size();
  404. outp.addSize(2); // make room for 16-bit size field
  405. if ((planetWorldId)&&(RR->topology->planetWorldTimestamp() > planetWorldTimestamp)&&(planetWorldId == RR->topology->planetWorldId())) {
  406. RR->topology->planet().serialize(outp,false);
  407. }
  408. if (!moonIdsAndTimestamps.empty()) {
  409. std::vector<World> moons(RR->topology->moons());
  410. for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
  411. for(std::vector< std::pair<uint64_t,uint64_t> >::const_iterator i(moonIdsAndTimestamps.begin());i!=moonIdsAndTimestamps.end();++i) {
  412. if (i->first == m->id()) {
  413. if (m->timestamp() > i->second)
  414. m->serialize(outp,false);
  415. break;
  416. }
  417. }
  418. }
  419. }
  420. outp.setAt<uint16_t>(worldUpdateSizeAt,(uint16_t)(outp.size() - (worldUpdateSizeAt + 2)));
  421. outp.armor(peer->key(),true,peer->aesKeysIfSupported());
  422. peer->recordOutgoingPacket(_path,outp.packetId(),outp.payloadLength(),outp.verb(),ZT_QOS_NO_FLOW,now);
  423. _path->send(RR,tPtr,outp.data(),outp.size(),now);
  424. peer->setRemoteVersion(protoVersion,vMajor,vMinor,vRevision); // important for this to go first so received() knows the version
  425. peer->received(tPtr,_path,hops(),pid,payloadLength(),Packet::VERB_HELLO,0,Packet::VERB_NOP,false,0,ZT_QOS_NO_FLOW);
  426. return true;
  427. }
  428. bool IncomingPacket::_doOK(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  429. {
  430. const Packet::Verb inReVerb = (Packet::Verb)(*this)[ZT_PROTO_VERB_OK_IDX_IN_RE_VERB];
  431. const uint64_t inRePacketId = at<uint64_t>(ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID);
  432. uint64_t networkId = 0;
  433. if (!RR->node->expectingReplyTo(inRePacketId))
  434. return true;
  435. switch(inReVerb) {
  436. case Packet::VERB_HELLO: {
  437. const uint64_t latency = RR->node->now() - at<uint64_t>(ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP);
  438. const unsigned int vProto = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION];
  439. const unsigned int vMajor = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION];
  440. const unsigned int vMinor = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION];
  441. const unsigned int vRevision = at<uint16_t>(ZT_PROTO_VERB_HELLO__OK__IDX_REVISION);
  442. if (vProto < ZT_PROTO_VERSION_MIN)
  443. return true;
  444. InetAddress externalSurfaceAddress;
  445. unsigned int ptr = ZT_PROTO_VERB_HELLO__OK__IDX_REVISION + 2;
  446. // Get reported external surface address if present
  447. if (ptr < size())
  448. ptr += externalSurfaceAddress.deserialize(*this,ptr);
  449. // Handle planet or moon updates if present
  450. if ((ptr + 2) <= size()) {
  451. const unsigned int worldsLen = at<uint16_t>(ptr); ptr += 2;
  452. if (RR->topology->shouldAcceptWorldUpdateFrom(peer->address())) {
  453. const unsigned int endOfWorlds = ptr + worldsLen;
  454. while (ptr < endOfWorlds) {
  455. World w;
  456. ptr += w.deserialize(*this,ptr);
  457. RR->topology->addWorld(tPtr,w,false);
  458. }
  459. } else {
  460. ptr += worldsLen;
  461. }
  462. }
  463. if (!hops()) {
  464. SharedPtr<Bond> bond = peer->bond();
  465. if (!bond) {
  466. _path->updateLatency((unsigned int)latency,RR->node->now());
  467. }
  468. }
  469. peer->setRemoteVersion(vProto,vMajor,vMinor,vRevision);
  470. if ((externalSurfaceAddress)&&(hops() == 0))
  471. RR->sa->iam(tPtr,peer->address(),_path->localSocket(),_path->address(),externalSurfaceAddress,RR->topology->isUpstream(peer->identity()),RR->node->now());
  472. } break;
  473. case Packet::VERB_WHOIS:
  474. if (RR->topology->isUpstream(peer->identity())) {
  475. const Identity id(*this,ZT_PROTO_VERB_WHOIS__OK__IDX_IDENTITY);
  476. RR->sw->doAnythingWaitingForPeer(tPtr,RR->topology->addPeer(tPtr,SharedPtr<Peer>(new Peer(RR,RR->identity,id))));
  477. }
  478. break;
  479. case Packet::VERB_NETWORK_CONFIG_REQUEST: {
  480. networkId = at<uint64_t>(ZT_PROTO_VERB_OK_IDX_PAYLOAD);
  481. const SharedPtr<Network> network(RR->node->network(networkId));
  482. if (network)
  483. network->handleConfigChunk(tPtr,packetId(),source(),*this,ZT_PROTO_VERB_OK_IDX_PAYLOAD);
  484. } break;
  485. case Packet::VERB_MULTICAST_GATHER: {
  486. networkId = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID);
  487. const SharedPtr<Network> network(RR->node->network(networkId));
  488. if (network) {
  489. 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));
  490. const unsigned int count = at<uint16_t>(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_GATHER_RESULTS + 4);
  491. 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));
  492. }
  493. } break;
  494. case Packet::VERB_MULTICAST_FRAME: {
  495. const unsigned int flags = (*this)[ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_FLAGS];
  496. networkId = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_NETWORK_ID);
  497. 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));
  498. const SharedPtr<Network> network(RR->node->network(networkId));
  499. if (network) {
  500. unsigned int offset = 0;
  501. if ((flags & 0x01) != 0) { // deprecated but still used by older peers
  502. CertificateOfMembership com;
  503. offset += com.deserialize(*this,ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_COM_AND_GATHER_RESULTS);
  504. if (com)
  505. network->addCredential(tPtr,com);
  506. }
  507. if ((flags & 0x02) != 0) {
  508. // OK(MULTICAST_FRAME) includes implicit gather results
  509. offset += ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_COM_AND_GATHER_RESULTS;
  510. unsigned int totalKnown = at<uint32_t>(offset); offset += 4;
  511. unsigned int count = at<uint16_t>(offset); offset += 2;
  512. RR->mc->addMultiple(tPtr,RR->node->now(),networkId,mg,field(offset,count * 5),count,totalKnown);
  513. }
  514. }
  515. } break;
  516. default: break;
  517. }
  518. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_OK,inRePacketId,inReVerb,false,networkId,ZT_QOS_NO_FLOW);
  519. return true;
  520. }
  521. bool IncomingPacket::_doWHOIS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  522. {
  523. if ((!RR->topology->amUpstream())&&(!peer->rateGateInboundWhoisRequest(RR->node->now())))
  524. return true;
  525. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  526. outp.append((unsigned char)Packet::VERB_WHOIS);
  527. outp.append(packetId());
  528. unsigned int count = 0;
  529. unsigned int ptr = ZT_PACKET_IDX_PAYLOAD;
  530. while ((ptr + ZT_ADDRESS_LENGTH) <= size()) {
  531. const Address addr(field(ptr,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  532. ptr += ZT_ADDRESS_LENGTH;
  533. const Identity id(RR->topology->getIdentity(tPtr,addr));
  534. if (id) {
  535. id.serialize(outp,false);
  536. ++count;
  537. } else {
  538. // Request unknown WHOIS from upstream from us (if we have one)
  539. RR->sw->requestWhois(tPtr,RR->node->now(),addr);
  540. }
  541. }
  542. if (count > 0) {
  543. outp.armor(peer->key(),true,peer->aesKeysIfSupported());
  544. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  545. }
  546. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_WHOIS,0,Packet::VERB_NOP,false,0,ZT_QOS_NO_FLOW);
  547. return true;
  548. }
  549. bool IncomingPacket::_doRENDEZVOUS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  550. {
  551. if (RR->topology->isUpstream(peer->identity())) {
  552. const Address with(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  553. const SharedPtr<Peer> rendezvousWith(RR->topology->getPeer(tPtr,with));
  554. if (rendezvousWith) {
  555. const unsigned int port = at<uint16_t>(ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT);
  556. const unsigned int addrlen = (*this)[ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN];
  557. if ((port > 0)&&((addrlen == 4)||(addrlen == 16))) {
  558. InetAddress atAddr(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS,addrlen),addrlen,port);
  559. if (RR->node->shouldUsePathForZeroTierTraffic(tPtr,with,_path->localSocket(),atAddr)) {
  560. const uint64_t junk = RR->node->prng();
  561. RR->node->putPacket(tPtr,_path->localSocket(),atAddr,&junk,4,2); // send low-TTL junk packet to 'open' local NAT(s) and stateful firewalls
  562. rendezvousWith->attemptToContactAt(tPtr,_path->localSocket(),atAddr,RR->node->now(),false);
  563. }
  564. }
  565. }
  566. }
  567. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_RENDEZVOUS,0,Packet::VERB_NOP,false,0,ZT_QOS_NO_FLOW);
  568. return true;
  569. }
  570. // Returns true if packet appears valid; pos and proto will be set
  571. static bool _ipv6GetPayload(const uint8_t *frameData,unsigned int frameLen,unsigned int &pos,unsigned int &proto)
  572. {
  573. if (frameLen < 40)
  574. return false;
  575. pos = 40;
  576. proto = frameData[6];
  577. while (pos <= frameLen) {
  578. switch(proto) {
  579. case 0: // hop-by-hop options
  580. case 43: // routing
  581. case 60: // destination options
  582. case 135: // mobility options
  583. if ((pos + 8) > frameLen)
  584. return false; // invalid!
  585. proto = frameData[pos];
  586. pos += ((unsigned int)frameData[pos + 1] * 8) + 8;
  587. break;
  588. //case 44: // fragment -- we currently can't parse these and they are deprecated in IPv6 anyway
  589. //case 50:
  590. //case 51: // IPSec ESP and AH -- we have to stop here since this is encrypted stuff
  591. default:
  592. return true;
  593. }
  594. }
  595. return false; // overflow == invalid
  596. }
  597. bool IncomingPacket::_doFRAME(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer,int32_t flowId)
  598. {
  599. int32_t _flowId = ZT_QOS_NO_FLOW;
  600. SharedPtr<Bond> bond = peer->bond();
  601. if (bond && bond->flowHashingEnabled()) {
  602. if (size() > ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD) {
  603. const unsigned int etherType = at<uint16_t>(ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE);
  604. const unsigned int frameLen = size() - ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  605. const uint8_t *const frameData = reinterpret_cast<const uint8_t *>(data()) + ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  606. if (etherType == ZT_ETHERTYPE_IPV4 && (frameLen >= 20)) {
  607. uint16_t srcPort = 0;
  608. uint16_t dstPort = 0;
  609. uint8_t proto = (reinterpret_cast<const uint8_t *>(frameData)[9]);
  610. const unsigned int headerLen = 4 * (reinterpret_cast<const uint8_t *>(frameData)[0] & 0xf);
  611. switch(proto) {
  612. case 0x01: // ICMP
  613. //flowId = 0x01;
  614. break;
  615. // All these start with 16-bit source and destination port in that order
  616. case 0x06: // TCP
  617. case 0x11: // UDP
  618. case 0x84: // SCTP
  619. case 0x88: // UDPLite
  620. if (frameLen > (headerLen + 4)) {
  621. unsigned int pos = headerLen + 0;
  622. srcPort = (reinterpret_cast<const uint8_t *>(frameData)[pos++]) << 8;
  623. srcPort |= (reinterpret_cast<const uint8_t *>(frameData)[pos]);
  624. pos++;
  625. dstPort = (reinterpret_cast<const uint8_t *>(frameData)[pos++]) << 8;
  626. dstPort |= (reinterpret_cast<const uint8_t *>(frameData)[pos]);
  627. _flowId = dstPort ^ srcPort ^ proto;
  628. }
  629. break;
  630. }
  631. }
  632. if (etherType == ZT_ETHERTYPE_IPV6 && (frameLen >= 40)) {
  633. uint16_t srcPort = 0;
  634. uint16_t dstPort = 0;
  635. unsigned int pos;
  636. unsigned int proto;
  637. _ipv6GetPayload((const uint8_t *)frameData, frameLen, pos, proto);
  638. switch(proto) {
  639. case 0x3A: // ICMPv6
  640. //flowId = 0x3A;
  641. break;
  642. // All these start with 16-bit source and destination port in that order
  643. case 0x06: // TCP
  644. case 0x11: // UDP
  645. case 0x84: // SCTP
  646. case 0x88: // UDPLite
  647. if (frameLen > (pos + 4)) {
  648. srcPort = (reinterpret_cast<const uint8_t *>(frameData)[pos++]) << 8;
  649. srcPort |= (reinterpret_cast<const uint8_t *>(frameData)[pos]);
  650. pos++;
  651. dstPort = (reinterpret_cast<const uint8_t *>(frameData)[pos++]) << 8;
  652. dstPort |= (reinterpret_cast<const uint8_t *>(frameData)[pos]);
  653. _flowId = dstPort ^ srcPort ^ proto;
  654. }
  655. break;
  656. default:
  657. break;
  658. }
  659. }
  660. }
  661. }
  662. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID);
  663. const SharedPtr<Network> network(RR->node->network(nwid));
  664. bool trustEstablished = false;
  665. if (network) {
  666. if (network->gate(tPtr,peer)) {
  667. trustEstablished = true;
  668. if (size() > ZT_PROTO_VERB_FRAME_IDX_PAYLOAD) {
  669. const unsigned int etherType = at<uint16_t>(ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE);
  670. const MAC sourceMac(peer->address(),nwid);
  671. const unsigned int frameLen = size() - ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  672. const uint8_t *const frameData = reinterpret_cast<const uint8_t *>(data()) + ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  673. if (network->filterIncomingPacket(tPtr,peer,RR->identity.address(),sourceMac,network->mac(),frameData,frameLen,etherType,0) > 0)
  674. RR->node->putFrame(tPtr,nwid,network->userPtr(),sourceMac,network->mac(),etherType,0,(const void *)frameData,frameLen);
  675. }
  676. } else {
  677. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  678. return false;
  679. }
  680. }
  681. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_FRAME,0,Packet::VERB_NOP,trustEstablished,nwid,_flowId);
  682. return true;
  683. }
  684. bool IncomingPacket::_doEXT_FRAME(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer,int32_t flowId)
  685. {
  686. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID);
  687. const SharedPtr<Network> network(RR->node->network(nwid));
  688. if (network) {
  689. const unsigned int flags = (*this)[ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS];
  690. unsigned int comLen = 0;
  691. if ((flags & 0x01) != 0) { // inline COM with EXT_FRAME is deprecated but still used with old peers
  692. CertificateOfMembership com;
  693. comLen = com.deserialize(*this,ZT_PROTO_VERB_EXT_FRAME_IDX_COM);
  694. if (com)
  695. network->addCredential(tPtr,com);
  696. }
  697. if (!network->gate(tPtr,peer)) {
  698. RR->t->incomingNetworkAccessDenied(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,true);
  699. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  700. return false;
  701. }
  702. if (size() > ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD) {
  703. const unsigned int etherType = at<uint16_t>(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE);
  704. 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);
  705. 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);
  706. const unsigned int frameLen = size() - (comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD);
  707. const uint8_t *const frameData = (const uint8_t *)field(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD,frameLen);
  708. if ((!from)||(from == network->mac())) {
  709. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,true,nwid,flowId); // trustEstablished because COM is okay
  710. return true;
  711. }
  712. switch (network->filterIncomingPacket(tPtr,peer,RR->identity.address(),from,to,frameData,frameLen,etherType,0)) {
  713. case 1:
  714. if (from != MAC(peer->address(),nwid)) {
  715. if (network->config().permitsBridging(peer->address())) {
  716. network->learnBridgeRoute(from,peer->address());
  717. } else {
  718. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,from,to,"bridging not allowed (remote)");
  719. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,true,nwid,flowId); // trustEstablished because COM is okay
  720. return true;
  721. }
  722. } else if (to != network->mac()) {
  723. if (to.isMulticast()) {
  724. if (network->config().multicastLimit == 0) {
  725. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,from,to,"multicast disabled");
  726. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,true,nwid,flowId); // trustEstablished because COM is okay
  727. return true;
  728. }
  729. } else if (!network->config().permitsBridging(RR->identity.address())) {
  730. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,from,to,"bridging not allowed (local)");
  731. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,true,nwid,flowId); // trustEstablished because COM is okay
  732. return true;
  733. }
  734. }
  735. // fall through -- 2 means accept regardless of bridging checks or other restrictions
  736. case 2:
  737. RR->node->putFrame(tPtr,nwid,network->userPtr(),from,to,etherType,0,(const void *)frameData,frameLen);
  738. break;
  739. }
  740. }
  741. if ((flags & 0x10) != 0) { // ACK requested
  742. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  743. outp.append((uint8_t)Packet::VERB_EXT_FRAME);
  744. outp.append((uint64_t)packetId());
  745. outp.append((uint64_t)nwid);
  746. const int64_t now = RR->node->now();
  747. outp.armor(peer->key(),true,peer->aesKeysIfSupported());
  748. peer->recordOutgoingPacket(_path,outp.packetId(),outp.payloadLength(),outp.verb(),ZT_QOS_NO_FLOW,now);
  749. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  750. }
  751. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,true,nwid,flowId);
  752. } else {
  753. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,false,nwid,flowId);
  754. }
  755. return true;
  756. }
  757. bool IncomingPacket::_doECHO(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  758. {
  759. uint64_t now = RR->node->now();
  760. if (!_path->rateGateEchoRequest(now)) {
  761. return true;
  762. }
  763. const uint64_t pid = packetId();
  764. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  765. outp.append((unsigned char)Packet::VERB_ECHO);
  766. outp.append((uint64_t)pid);
  767. if (size() > ZT_PACKET_IDX_PAYLOAD)
  768. outp.append(reinterpret_cast<const unsigned char *>(data()) + ZT_PACKET_IDX_PAYLOAD,size() - ZT_PACKET_IDX_PAYLOAD);
  769. outp.armor(peer->key(),true,peer->aesKeysIfSupported());
  770. peer->recordOutgoingPacket(_path,outp.packetId(),outp.payloadLength(),outp.verb(),ZT_QOS_NO_FLOW,now);
  771. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  772. peer->received(tPtr,_path,hops(),pid,payloadLength(),Packet::VERB_ECHO,0,Packet::VERB_NOP,false,0,ZT_QOS_NO_FLOW);
  773. return true;
  774. }
  775. bool IncomingPacket::_doMULTICAST_LIKE(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  776. {
  777. const int64_t now = RR->node->now();
  778. bool authorized = false;
  779. uint64_t lastNwid = 0;
  780. // Packet contains a series of 18-byte network,MAC,ADI tuples
  781. for(unsigned int ptr=ZT_PACKET_IDX_PAYLOAD;ptr<size();ptr+=18) {
  782. const uint64_t nwid = at<uint64_t>(ptr);
  783. if (nwid != lastNwid) {
  784. lastNwid = nwid;
  785. SharedPtr<Network> network(RR->node->network(nwid));
  786. if (network)
  787. authorized = network->gate(tPtr,peer);
  788. if (!authorized)
  789. authorized = ((RR->topology->amUpstream())||(RR->node->localControllerHasAuthorized(now,nwid,peer->address())));
  790. }
  791. if (authorized)
  792. RR->mc->add(tPtr,now,nwid,MulticastGroup(MAC(field(ptr + 8,6),6),at<uint32_t>(ptr + 14)),peer->address());
  793. }
  794. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_MULTICAST_LIKE,0,Packet::VERB_NOP,false,0,ZT_QOS_NO_FLOW);
  795. return true;
  796. }
  797. bool IncomingPacket::_doNETWORK_CREDENTIALS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  798. {
  799. if (!peer->rateGateCredentialsReceived(RR->node->now()))
  800. return true;
  801. CertificateOfMembership com;
  802. Capability cap;
  803. Tag tag;
  804. Revocation revocation;
  805. CertificateOfOwnership coo;
  806. bool trustEstablished = false;
  807. SharedPtr<Network> network;
  808. unsigned int p = ZT_PACKET_IDX_PAYLOAD;
  809. while ((p < size())&&((*this)[p] != 0)) {
  810. p += com.deserialize(*this,p);
  811. if (com) {
  812. network = RR->node->network(com.networkId());
  813. if (network) {
  814. switch (network->addCredential(tPtr,com)) {
  815. case Membership::ADD_REJECTED:
  816. break;
  817. case Membership::ADD_ACCEPTED_NEW:
  818. case Membership::ADD_ACCEPTED_REDUNDANT:
  819. trustEstablished = true;
  820. break;
  821. case Membership::ADD_DEFERRED_FOR_WHOIS:
  822. return false;
  823. }
  824. }
  825. }
  826. }
  827. ++p; // skip trailing 0 after COMs if present
  828. if (p < size()) { // older ZeroTier versions do not send capabilities, tags, or revocations
  829. const unsigned int numCapabilities = at<uint16_t>(p); p += 2;
  830. for(unsigned int i=0;i<numCapabilities;++i) {
  831. p += cap.deserialize(*this,p);
  832. if ((!network)||(network->id() != cap.networkId()))
  833. network = RR->node->network(cap.networkId());
  834. if (network) {
  835. switch (network->addCredential(tPtr,cap)) {
  836. case Membership::ADD_REJECTED:
  837. break;
  838. case Membership::ADD_ACCEPTED_NEW:
  839. case Membership::ADD_ACCEPTED_REDUNDANT:
  840. trustEstablished = true;
  841. break;
  842. case Membership::ADD_DEFERRED_FOR_WHOIS:
  843. return false;
  844. }
  845. }
  846. }
  847. if (p >= size()) return true;
  848. const unsigned int numTags = at<uint16_t>(p); p += 2;
  849. for(unsigned int i=0;i<numTags;++i) {
  850. p += tag.deserialize(*this,p);
  851. if ((!network)||(network->id() != tag.networkId()))
  852. network = RR->node->network(tag.networkId());
  853. if (network) {
  854. switch (network->addCredential(tPtr,tag)) {
  855. case Membership::ADD_REJECTED:
  856. break;
  857. case Membership::ADD_ACCEPTED_NEW:
  858. case Membership::ADD_ACCEPTED_REDUNDANT:
  859. trustEstablished = true;
  860. break;
  861. case Membership::ADD_DEFERRED_FOR_WHOIS:
  862. return false;
  863. }
  864. }
  865. }
  866. if (p >= size()) return true;
  867. const unsigned int numRevocations = at<uint16_t>(p); p += 2;
  868. for(unsigned int i=0;i<numRevocations;++i) {
  869. p += revocation.deserialize(*this,p);
  870. if ((!network)||(network->id() != revocation.networkId()))
  871. network = RR->node->network(revocation.networkId());
  872. if (network) {
  873. switch(network->addCredential(tPtr,peer->address(),revocation)) {
  874. case Membership::ADD_REJECTED:
  875. break;
  876. case Membership::ADD_ACCEPTED_NEW:
  877. case Membership::ADD_ACCEPTED_REDUNDANT:
  878. trustEstablished = true;
  879. break;
  880. case Membership::ADD_DEFERRED_FOR_WHOIS:
  881. return false;
  882. }
  883. }
  884. }
  885. if (p >= size()) return true;
  886. const unsigned int numCoos = at<uint16_t>(p); p += 2;
  887. for(unsigned int i=0;i<numCoos;++i) {
  888. p += coo.deserialize(*this,p);
  889. if ((!network)||(network->id() != coo.networkId()))
  890. network = RR->node->network(coo.networkId());
  891. if (network) {
  892. switch(network->addCredential(tPtr,coo)) {
  893. case Membership::ADD_REJECTED:
  894. break;
  895. case Membership::ADD_ACCEPTED_NEW:
  896. case Membership::ADD_ACCEPTED_REDUNDANT:
  897. trustEstablished = true;
  898. break;
  899. case Membership::ADD_DEFERRED_FOR_WHOIS:
  900. return false;
  901. }
  902. }
  903. }
  904. }
  905. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_NETWORK_CREDENTIALS,0,Packet::VERB_NOP,trustEstablished,(network) ? network->id() : 0,ZT_QOS_NO_FLOW);
  906. return true;
  907. }
  908. bool IncomingPacket::_doNETWORK_CONFIG_REQUEST(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  909. {
  910. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID);
  911. const unsigned int hopCount = hops();
  912. const uint64_t requestPacketId = packetId();
  913. if (RR->localNetworkController) {
  914. 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;
  915. const char *metaDataBytes = (metaDataLength != 0) ? (const char *)field(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT,metaDataLength) : (const char *)0;
  916. const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> metaData(metaDataBytes,metaDataLength);
  917. RR->localNetworkController->request(nwid,(hopCount > 0) ? InetAddress() : _path->address(),requestPacketId,peer->identity(),metaData);
  918. } else {
  919. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_ERROR);
  920. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  921. outp.append(requestPacketId);
  922. outp.append((unsigned char)Packet::ERROR_UNSUPPORTED_OPERATION);
  923. outp.append(nwid);
  924. outp.armor(peer->key(),true,peer->aesKeysIfSupported());
  925. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  926. }
  927. peer->received(tPtr,_path,hopCount,requestPacketId,payloadLength(),Packet::VERB_NETWORK_CONFIG_REQUEST,0,Packet::VERB_NOP,false,nwid,ZT_QOS_NO_FLOW);
  928. return true;
  929. }
  930. bool IncomingPacket::_doNETWORK_CONFIG(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  931. {
  932. const SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PACKET_IDX_PAYLOAD)));
  933. if (network) {
  934. const uint64_t configUpdateId = network->handleConfigChunk(tPtr,packetId(),source(),*this,ZT_PACKET_IDX_PAYLOAD);
  935. if (configUpdateId) {
  936. Packet outp(peer->address(), RR->identity.address(), Packet::VERB_OK);
  937. outp.append((uint8_t)Packet::VERB_ECHO);
  938. outp.append((uint64_t)packetId());
  939. outp.append((uint64_t)network->id());
  940. outp.append((uint64_t)configUpdateId);
  941. const int64_t now = RR->node->now();
  942. outp.armor(peer->key(),true,peer->aesKeysIfSupported());
  943. peer->recordOutgoingPacket(_path,outp.packetId(),outp.payloadLength(),outp.verb(),ZT_QOS_NO_FLOW,now);
  944. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  945. }
  946. }
  947. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_NETWORK_CONFIG,0,Packet::VERB_NOP,false,(network) ? network->id() : 0,ZT_QOS_NO_FLOW);
  948. return true;
  949. }
  950. bool IncomingPacket::_doMULTICAST_GATHER(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  951. {
  952. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID);
  953. const unsigned int flags = (*this)[ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS];
  954. const MulticastGroup mg(MAC(field(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC,6),6),at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI));
  955. const unsigned int gatherLimit = at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_GATHER_LIMIT);
  956. const SharedPtr<Network> network(RR->node->network(nwid));
  957. if ((flags & 0x01) != 0) {
  958. try {
  959. CertificateOfMembership com;
  960. com.deserialize(*this,ZT_PROTO_VERB_MULTICAST_GATHER_IDX_COM);
  961. if ((com)&&(network))
  962. network->addCredential(tPtr,com);
  963. } catch ( ... ) {} // discard invalid COMs
  964. }
  965. const bool trustEstablished = (network) ? network->gate(tPtr,peer) : false;
  966. const int64_t now = RR->node->now();
  967. if ((gatherLimit > 0)&&((trustEstablished)||(RR->topology->amUpstream())||(RR->node->localControllerHasAuthorized(now,nwid,peer->address())))) {
  968. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  969. outp.append((unsigned char)Packet::VERB_MULTICAST_GATHER);
  970. outp.append(packetId());
  971. outp.append(nwid);
  972. mg.mac().appendTo(outp);
  973. outp.append((uint32_t)mg.adi());
  974. const unsigned int gatheredLocally = RR->mc->gather(peer->address(),nwid,mg,outp,gatherLimit);
  975. if (gatheredLocally > 0) {
  976. outp.armor(peer->key(),true,peer->aesKeysIfSupported());
  977. peer->recordOutgoingPacket(_path,outp.packetId(),outp.payloadLength(),outp.verb(),ZT_QOS_NO_FLOW,now);
  978. _path->send(RR,tPtr,outp.data(),outp.size(),now);
  979. }
  980. }
  981. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_MULTICAST_GATHER,0,Packet::VERB_NOP,trustEstablished,nwid,ZT_QOS_NO_FLOW);
  982. return true;
  983. }
  984. bool IncomingPacket::_doMULTICAST_FRAME(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  985. {
  986. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID);
  987. const unsigned int flags = (*this)[ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS];
  988. const SharedPtr<Network> network(RR->node->network(nwid));
  989. if (network) {
  990. // Offset -- size of optional fields added to position of later fields
  991. unsigned int offset = 0;
  992. if ((flags & 0x01) != 0) {
  993. // This is deprecated but may still be sent by old peers
  994. CertificateOfMembership com;
  995. offset += com.deserialize(*this,ZT_PROTO_VERB_MULTICAST_FRAME_IDX_COM);
  996. if (com)
  997. network->addCredential(tPtr,com);
  998. }
  999. if (!network->gate(tPtr,peer)) {
  1000. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  1001. return false;
  1002. }
  1003. unsigned int gatherLimit = 0;
  1004. if ((flags & 0x02) != 0) {
  1005. gatherLimit = at<uint32_t>(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_GATHER_LIMIT);
  1006. offset += 4;
  1007. }
  1008. MAC from;
  1009. if ((flags & 0x04) != 0) {
  1010. from.setTo(field(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SOURCE_MAC,6),6);
  1011. offset += 6;
  1012. } else {
  1013. from.fromAddress(peer->address(),nwid);
  1014. }
  1015. const MulticastGroup to(MAC(field(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_MAC,6),6),at<uint32_t>(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_ADI));
  1016. const unsigned int etherType = at<uint16_t>(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE);
  1017. const unsigned int frameLen = size() - (offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME);
  1018. if (network->config().multicastLimit == 0) {
  1019. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_MULTICAST_FRAME,from,to.mac(),"multicast disabled");
  1020. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,false,nwid,ZT_QOS_NO_FLOW);
  1021. return true;
  1022. }
  1023. if ((frameLen > 0)&&(frameLen <= ZT_MAX_MTU)) {
  1024. if (!to.mac().isMulticast()) {
  1025. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),source(),hops(),Packet::VERB_MULTICAST_FRAME,"destination not multicast");
  1026. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,true,nwid,ZT_QOS_NO_FLOW); // trustEstablished because COM is okay
  1027. return true;
  1028. }
  1029. if ((!from)||(from.isMulticast())||(from == network->mac())) {
  1030. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),source(),hops(),Packet::VERB_MULTICAST_FRAME,"invalid source MAC");
  1031. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,true,nwid,ZT_QOS_NO_FLOW); // trustEstablished because COM is okay
  1032. return true;
  1033. }
  1034. const uint8_t *const frameData = (const uint8_t *)field(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME,frameLen);
  1035. if ((flags & 0x08)&&(network->config().isMulticastReplicator(RR->identity.address())))
  1036. RR->mc->send(tPtr,RR->node->now(),network,peer->address(),to,from,etherType,frameData,frameLen);
  1037. if (from != MAC(peer->address(),nwid)) {
  1038. if (network->config().permitsBridging(peer->address())) {
  1039. network->learnBridgeRoute(from,peer->address());
  1040. } else {
  1041. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_MULTICAST_FRAME,from,to.mac(),"bridging not allowed (remote)");
  1042. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,true,nwid,ZT_QOS_NO_FLOW); // trustEstablished because COM is okay
  1043. return true;
  1044. }
  1045. }
  1046. if (network->filterIncomingPacket(tPtr,peer,RR->identity.address(),from,to.mac(),frameData,frameLen,etherType,0) > 0)
  1047. RR->node->putFrame(tPtr,nwid,network->userPtr(),from,to.mac(),etherType,0,(const void *)frameData,frameLen);
  1048. }
  1049. if (gatherLimit) {
  1050. Packet outp(source(),RR->identity.address(),Packet::VERB_OK);
  1051. outp.append((unsigned char)Packet::VERB_MULTICAST_FRAME);
  1052. outp.append(packetId());
  1053. outp.append(nwid);
  1054. to.mac().appendTo(outp);
  1055. outp.append((uint32_t)to.adi());
  1056. outp.append((unsigned char)0x02); // flag 0x02 = contains gather results
  1057. if (RR->mc->gather(peer->address(),nwid,to,outp,gatherLimit)) {
  1058. const int64_t now = RR->node->now();
  1059. outp.armor(peer->key(),true,peer->aesKeysIfSupported());
  1060. peer->recordOutgoingPacket(_path,outp.packetId(),outp.payloadLength(),outp.verb(),ZT_QOS_NO_FLOW,now);
  1061. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  1062. }
  1063. }
  1064. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,true,nwid,ZT_QOS_NO_FLOW);
  1065. }
  1066. return true;
  1067. }
  1068. bool IncomingPacket::_doPUSH_DIRECT_PATHS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  1069. {
  1070. const int64_t now = RR->node->now();
  1071. if (!peer->rateGatePushDirectPaths(now)) {
  1072. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_PUSH_DIRECT_PATHS,0,Packet::VERB_NOP,false,0,ZT_QOS_NO_FLOW);
  1073. return true;
  1074. }
  1075. // Second, limit addresses by scope and type
  1076. uint8_t countPerScope[ZT_INETADDRESS_MAX_SCOPE+1][2]; // [][0] is v4, [][1] is v6
  1077. memset(countPerScope,0,sizeof(countPerScope));
  1078. unsigned int count = at<uint16_t>(ZT_PACKET_IDX_PAYLOAD);
  1079. unsigned int ptr = ZT_PACKET_IDX_PAYLOAD + 2;
  1080. while (count--) { // if ptr overflows Buffer will throw
  1081. unsigned int flags = (*this)[ptr++];
  1082. unsigned int extLen = at<uint16_t>(ptr); ptr += 2;
  1083. ptr += extLen; // unused right now
  1084. unsigned int addrType = (*this)[ptr++];
  1085. unsigned int addrLen = (*this)[ptr++];
  1086. switch(addrType) {
  1087. case 4: {
  1088. const InetAddress a(field(ptr,4),4,at<uint16_t>(ptr + 4));
  1089. if (
  1090. ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_FORGET_PATH) == 0) && // not being told to forget
  1091. (!( ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT) == 0) && (peer->hasActivePathTo(now,a)) )) && // not already known
  1092. (RR->node->shouldUsePathForZeroTierTraffic(tPtr,peer->address(),_path->localSocket(),a)) ) // should use path
  1093. {
  1094. if ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT) != 0) {
  1095. peer->clusterRedirect(tPtr,_path,a,now);
  1096. } else if (++countPerScope[(int)a.ipScope()][0] <= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY) {
  1097. peer->attemptToContactAt(tPtr,InetAddress(),a,now,false);
  1098. }
  1099. }
  1100. } break;
  1101. case 6: {
  1102. const InetAddress a(field(ptr,16),16,at<uint16_t>(ptr + 16));
  1103. if (
  1104. ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_FORGET_PATH) == 0) && // not being told to forget
  1105. (!( ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT) == 0) && (peer->hasActivePathTo(now,a)) )) && // not already known
  1106. (RR->node->shouldUsePathForZeroTierTraffic(tPtr,peer->address(),_path->localSocket(),a)) ) // should use path
  1107. {
  1108. if ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT) != 0) {
  1109. peer->clusterRedirect(tPtr,_path,a,now);
  1110. } else if (++countPerScope[(int)a.ipScope()][1] <= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY) {
  1111. peer->attemptToContactAt(tPtr,InetAddress(),a,now,false);
  1112. }
  1113. }
  1114. } break;
  1115. }
  1116. ptr += addrLen;
  1117. }
  1118. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_PUSH_DIRECT_PATHS,0,Packet::VERB_NOP,false,0,ZT_QOS_NO_FLOW);
  1119. return true;
  1120. }
  1121. bool IncomingPacket::_doUSER_MESSAGE(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  1122. {
  1123. if (likely(size() >= (ZT_PACKET_IDX_PAYLOAD + 8))) {
  1124. ZT_UserMessage um;
  1125. um.origin = peer->address().toInt();
  1126. um.typeId = at<uint64_t>(ZT_PACKET_IDX_PAYLOAD);
  1127. um.data = reinterpret_cast<const void *>(reinterpret_cast<const uint8_t *>(data()) + ZT_PACKET_IDX_PAYLOAD + 8);
  1128. um.length = size() - (ZT_PACKET_IDX_PAYLOAD + 8);
  1129. RR->node->postEvent(tPtr,ZT_EVENT_USER_MESSAGE,reinterpret_cast<const void *>(&um));
  1130. }
  1131. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_USER_MESSAGE,0,Packet::VERB_NOP,false,0,ZT_QOS_NO_FLOW);
  1132. return true;
  1133. }
  1134. bool IncomingPacket::_doREMOTE_TRACE(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  1135. {
  1136. ZT_RemoteTrace rt;
  1137. const char *ptr = reinterpret_cast<const char *>(data()) + ZT_PACKET_IDX_PAYLOAD;
  1138. const char *const eof = reinterpret_cast<const char *>(data()) + size();
  1139. rt.origin = peer->address().toInt();
  1140. rt.data = const_cast<char *>(ptr); // start of first string
  1141. while (ptr < eof) {
  1142. if (!*ptr) { // end of string
  1143. rt.len = (unsigned int)(ptr - rt.data);
  1144. if ((rt.len > 0)&&(rt.len <= ZT_MAX_REMOTE_TRACE_SIZE)) {
  1145. RR->node->postEvent(tPtr,ZT_EVENT_REMOTE_TRACE,&rt);
  1146. }
  1147. rt.data = const_cast<char *>(++ptr); // start of next string, if any
  1148. } else {
  1149. ++ptr;
  1150. }
  1151. }
  1152. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_REMOTE_TRACE,0,Packet::VERB_NOP,false,0,ZT_QOS_NO_FLOW);
  1153. return true;
  1154. }
  1155. bool IncomingPacket::_doPATH_NEGOTIATION_REQUEST(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  1156. {
  1157. uint64_t now = RR->node->now();
  1158. SharedPtr<Bond> bond = peer->bond();
  1159. if (!bond || !bond->rateGatePathNegotiation(now, _path)) {
  1160. return true;
  1161. }
  1162. if (payloadLength() != sizeof(int16_t)) {
  1163. return true;
  1164. }
  1165. int16_t remoteUtility = 0;
  1166. memcpy(&remoteUtility, payload(), sizeof(int16_t));
  1167. if (peer->bond()) {
  1168. peer->bond()->processIncomingPathNegotiationRequest(now, _path, Utils::ntoh(remoteUtility));
  1169. }
  1170. return true;
  1171. }
  1172. void IncomingPacket::_sendErrorNeedCredentials(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer,const uint64_t nwid)
  1173. {
  1174. Packet outp(source(),RR->identity.address(),Packet::VERB_ERROR);
  1175. outp.append((uint8_t)verb());
  1176. outp.append(packetId());
  1177. outp.append((uint8_t)Packet::ERROR_NEED_MEMBERSHIP_CERTIFICATE);
  1178. outp.append(nwid);
  1179. outp.armor(peer->key(),true,peer->aesKeysIfSupported());
  1180. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  1181. }
  1182. } // namespace ZeroTier