IncomingPacket.cpp 55 KB

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