2
0

IncomingPacket.cpp 54 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. bool trusted = false;
  45. if (c == ZT_PROTO_CIPHER_SUITE__NO_CRYPTO_TRUSTED_PATH) {
  46. // If this is marked as a packet via a trusted path, check source address and path ID.
  47. // Obviously if no trusted paths are configured this always returns false and such
  48. // packets are dropped on the floor.
  49. const uint64_t tpid = trustedPathId();
  50. if (RR->topology->shouldInboundPathBeTrusted(_path->address(),tpid)) {
  51. trusted = true;
  52. } else {
  53. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,packetId(),sourceAddress,hops(),"path not trusted");
  54. return true;
  55. }
  56. } else if ((c == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE)&&(verb() == Packet::VERB_HELLO)) {
  57. // Only HELLO is allowed in the clear, but will still have a MAC
  58. return _doHELLO(RR,tPtr,false);
  59. }
  60. const SharedPtr<Peer> peer(RR->topology->getPeer(tPtr,sourceAddress));
  61. if (peer) {
  62. if (!trusted) {
  63. if (!dearmor(peer->key(), peer->aesKeys())) {
  64. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,packetId(),sourceAddress,hops(),"invalid MAC");
  65. peer->recordIncomingInvalidPacket(_path);
  66. return true;
  67. }
  68. }
  69. if (!uncompress()) {
  70. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),sourceAddress,hops(),Packet::VERB_NOP,"LZ4 decompression failed");
  71. return true;
  72. }
  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->pushCredentialsNow(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. fprintf(stderr, "authVer == 1\n");
  186. char authenticationURL[2048];
  187. if (authInfo.get(ZT_AUTHINFO_DICT_KEY_AUTHENTICATION_URL, authenticationURL, sizeof(authenticationURL)) > 0) {
  188. authenticationURL[sizeof(authenticationURL) - 1] = 0; // ensure always zero terminated
  189. network->setAuthenticationRequired(tPtr, authenticationURL);
  190. }
  191. } else if (authVer == 1) {
  192. fprintf(stderr, "authVer == 2\n");
  193. char issuerURL[2048] = { 0 };
  194. char centralAuthURL[2048] = { 0 };
  195. char ssoNonce[64] = { 0 };
  196. char ssoState[128] = {0};
  197. char ssoClientID[256] = { 0 };
  198. if (authInfo.get(ZT_AUTHINFO_DICT_KEY_ISSUER_URL, issuerURL, sizeof(issuerURL)) > 0) {
  199. issuerURL[sizeof(issuerURL) - 1] = 0;
  200. }
  201. if (authInfo.get(ZT_AUTHINFO_DICT_KEY_CENTRAL_ENDPOINT_URL, centralAuthURL, sizeof(centralAuthURL))>0) {
  202. centralAuthURL[sizeof(centralAuthURL) - 1] = 0;
  203. }
  204. if (authInfo.get(ZT_AUTHINFO_DICT_KEY_NONCE, ssoNonce, sizeof(ssoNonce)) > 0) {
  205. ssoNonce[sizeof(ssoNonce) - 1] = 0;
  206. }
  207. if (authInfo.get(ZT_AUTHINFO_DICT_KEY_STATE, ssoState, sizeof(ssoState)) > 0) {
  208. ssoState[sizeof(ssoState) - 1] = 0;
  209. }
  210. if (authInfo.get(ZT_AUTHINFO_DICT_KEY_CLIENT_ID, ssoClientID, sizeof(ssoClientID)) > 0) {
  211. ssoClientID[sizeof(ssoClientID) - 1] = 0;
  212. }
  213. network->setAuthenticationRequired(tPtr, issuerURL, centralAuthURL, ssoClientID, ssoNonce, ssoState);
  214. }
  215. }
  216. } else {
  217. fprintf(stderr, "authinfo??????\n");
  218. network->setAuthenticationRequired(tPtr, "");
  219. }
  220. }
  221. } break;
  222. default: break;
  223. }
  224. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_ERROR,inRePacketId,inReVerb,false,networkId,ZT_QOS_NO_FLOW);
  225. return true;
  226. }
  227. bool IncomingPacket::_doQOS_MEASUREMENT(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  228. {
  229. SharedPtr<Bond> bond = peer->bond();
  230. if (!bond || !bond->rateGateQoS(RR->node->now(), _path)) {
  231. return true;
  232. }
  233. if (payloadLength() > ZT_QOS_MAX_PACKET_SIZE || payloadLength() < ZT_QOS_MIN_PACKET_SIZE) {
  234. return true; // ignore
  235. }
  236. const int64_t now = RR->node->now();
  237. uint64_t rx_id[ZT_QOS_TABLE_SIZE];
  238. uint16_t rx_ts[ZT_QOS_TABLE_SIZE];
  239. char *begin = (char *)payload();
  240. char *ptr = begin;
  241. int count = 0;
  242. unsigned int len = payloadLength();
  243. // Read packet IDs and latency compensation intervals for each packet tracked by this QoS packet
  244. while (ptr < (begin + len) && (count < ZT_QOS_TABLE_SIZE)) {
  245. memcpy((void*)&rx_id[count], ptr, sizeof(uint64_t));
  246. ptr+=sizeof(uint64_t);
  247. memcpy((void*)&rx_ts[count], ptr, sizeof(uint16_t));
  248. ptr+=sizeof(uint16_t);
  249. count++;
  250. }
  251. if (bond) {
  252. bond->receivedQoS(_path, now, count, rx_id, rx_ts);
  253. }
  254. return true;
  255. }
  256. bool IncomingPacket::_doHELLO(const RuntimeEnvironment *RR,void *tPtr,const bool alreadyAuthenticated)
  257. {
  258. const int64_t now = RR->node->now();
  259. const uint64_t pid = packetId();
  260. const Address fromAddress(source());
  261. const unsigned int protoVersion = (*this)[ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION];
  262. const unsigned int vMajor = (*this)[ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION];
  263. const unsigned int vMinor = (*this)[ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION];
  264. const unsigned int vRevision = at<uint16_t>(ZT_PROTO_VERB_HELLO_IDX_REVISION);
  265. const int64_t timestamp = at<int64_t>(ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP);
  266. Identity id;
  267. unsigned int ptr = ZT_PROTO_VERB_HELLO_IDX_IDENTITY + id.deserialize(*this,ZT_PROTO_VERB_HELLO_IDX_IDENTITY);
  268. if (protoVersion < ZT_PROTO_VERSION_MIN) {
  269. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"protocol version too old");
  270. return true;
  271. }
  272. if (fromAddress != id.address()) {
  273. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"identity/address mismatch");
  274. return true;
  275. }
  276. SharedPtr<Peer> peer(RR->topology->getPeer(tPtr,id.address()));
  277. if (peer) {
  278. // We already have an identity with this address -- check for collisions
  279. if (!alreadyAuthenticated) {
  280. if (peer->identity() != id) {
  281. // Identity is different from the one we already have -- address collision
  282. // Check rate limits
  283. if (!RR->node->rateGateIdentityVerification(now,_path->address()))
  284. return true;
  285. uint8_t key[ZT_SYMMETRIC_KEY_SIZE];
  286. if (RR->identity.agree(id,key)) {
  287. if (dearmor(key, peer->aesKeysIfSupported())) { // ensure packet is authentic, otherwise drop
  288. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"address collision");
  289. Packet outp(id.address(),RR->identity.address(),Packet::VERB_ERROR);
  290. outp.append((uint8_t)Packet::VERB_HELLO);
  291. outp.append((uint64_t)pid);
  292. outp.append((uint8_t)Packet::ERROR_IDENTITY_COLLISION);
  293. outp.armor(key,true,peer->aesKeysIfSupported());
  294. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  295. } else {
  296. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,pid,fromAddress,hops(),"invalid MAC");
  297. }
  298. } else {
  299. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,pid,fromAddress,hops(),"invalid identity");
  300. }
  301. return true;
  302. } else {
  303. // Identity is the same as the one we already have -- check packet integrity
  304. if (!dearmor(peer->key(), peer->aesKeysIfSupported())) {
  305. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,pid,fromAddress,hops(),"invalid MAC");
  306. return true;
  307. }
  308. // Continue at // VALID
  309. }
  310. } // else if alreadyAuthenticated then continue at // VALID
  311. } else {
  312. // We don't already have an identity with this address -- validate and learn it
  313. // Sanity check: this basically can't happen
  314. if (alreadyAuthenticated) {
  315. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"illegal alreadyAuthenticated state");
  316. return true;
  317. }
  318. // Check rate limits
  319. if (!RR->node->rateGateIdentityVerification(now,_path->address())) {
  320. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"rate limit exceeded");
  321. return true;
  322. }
  323. // Check packet integrity and MAC (this is faster than locallyValidate() so do it first to filter out total crap)
  324. SharedPtr<Peer> newPeer(new Peer(RR,RR->identity,id));
  325. if (!dearmor(newPeer->key(), newPeer->aesKeysIfSupported())) {
  326. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,pid,fromAddress,hops(),"invalid MAC");
  327. return true;
  328. }
  329. // Check that identity's address is valid as per the derivation function
  330. if (!id.locallyValidate()) {
  331. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"invalid identity");
  332. return true;
  333. }
  334. peer = RR->topology->addPeer(tPtr,newPeer);
  335. // Continue at // VALID
  336. }
  337. // VALID -- if we made it here, packet passed identity and authenticity checks!
  338. // Get external surface address if present (was not in old versions)
  339. InetAddress externalSurfaceAddress;
  340. if (ptr < size()) {
  341. ptr += externalSurfaceAddress.deserialize(*this,ptr);
  342. if ((externalSurfaceAddress)&&(hops() == 0))
  343. RR->sa->iam(tPtr,id.address(),_path->localSocket(),_path->address(),externalSurfaceAddress,RR->topology->isUpstream(id),now);
  344. }
  345. // Get primary planet world ID and world timestamp if present
  346. uint64_t planetWorldId = 0;
  347. uint64_t planetWorldTimestamp = 0;
  348. if ((ptr + 16) <= size()) {
  349. planetWorldId = at<uint64_t>(ptr); ptr += 8;
  350. planetWorldTimestamp = at<uint64_t>(ptr); ptr += 8;
  351. }
  352. std::vector< std::pair<uint64_t,uint64_t> > moonIdsAndTimestamps;
  353. if (ptr < size()) {
  354. // Remainder of packet, if present, is encrypted
  355. cryptField(peer->key(),ptr,size() - ptr);
  356. // Get moon IDs and timestamps if present
  357. if ((ptr + 2) <= size()) {
  358. const unsigned int numMoons = at<uint16_t>(ptr); ptr += 2;
  359. for(unsigned int i=0;i<numMoons;++i) {
  360. if ((World::Type)(*this)[ptr++] == World::TYPE_MOON)
  361. moonIdsAndTimestamps.push_back(std::pair<uint64_t,uint64_t>(at<uint64_t>(ptr),at<uint64_t>(ptr + 8)));
  362. ptr += 16;
  363. }
  364. }
  365. }
  366. // Send OK(HELLO) with an echo of the packet's timestamp and some of the same
  367. // information about us: version, sent-to address, etc.
  368. Packet outp(id.address(),RR->identity.address(),Packet::VERB_OK);
  369. outp.append((unsigned char)Packet::VERB_HELLO);
  370. outp.append((uint64_t)pid);
  371. outp.append((uint64_t)timestamp);
  372. outp.append((unsigned char)ZT_PROTO_VERSION);
  373. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  374. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  375. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  376. if (protoVersion >= 5) {
  377. _path->address().serialize(outp);
  378. } else {
  379. /* LEGACY COMPATIBILITY HACK:
  380. *
  381. * For a while now (since 1.0.3), ZeroTier has recognized changes in
  382. * its network environment empirically by examining its external network
  383. * address as reported by trusted peers. In versions prior to 1.1.0
  384. * (protocol version < 5), they did this by saving a snapshot of this
  385. * information (in SelfAwareness.hpp) keyed by reporting device ID and
  386. * address type.
  387. *
  388. * This causes problems when clustering is combined with symmetric NAT.
  389. * Symmetric NAT remaps ports, so different endpoints in a cluster will
  390. * report back different exterior addresses. Since the old code keys
  391. * this by device ID and not sending physical address and compares the
  392. * entire address including port, it constantly thinks its external
  393. * surface is changing and resets connections when talking to a cluster.
  394. *
  395. * In new code we key by sending physical address and device and we also
  396. * take the more conservative position of only interpreting changes in
  397. * IP address (neglecting port) as a change in network topology that
  398. * necessitates a reset. But we can make older clients work here by
  399. * nulling out the port field. Since this info is only used for empirical
  400. * detection of link changes, it doesn't break anything else.
  401. */
  402. InetAddress tmpa(_path->address());
  403. tmpa.setPort(0);
  404. tmpa.serialize(outp);
  405. }
  406. const unsigned int worldUpdateSizeAt = outp.size();
  407. outp.addSize(2); // make room for 16-bit size field
  408. if ((planetWorldId)&&(RR->topology->planetWorldTimestamp() > planetWorldTimestamp)&&(planetWorldId == RR->topology->planetWorldId())) {
  409. RR->topology->planet().serialize(outp,false);
  410. }
  411. if (!moonIdsAndTimestamps.empty()) {
  412. std::vector<World> moons(RR->topology->moons());
  413. for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
  414. for(std::vector< std::pair<uint64_t,uint64_t> >::const_iterator i(moonIdsAndTimestamps.begin());i!=moonIdsAndTimestamps.end();++i) {
  415. if (i->first == m->id()) {
  416. if (m->timestamp() > i->second)
  417. m->serialize(outp,false);
  418. break;
  419. }
  420. }
  421. }
  422. }
  423. outp.setAt<uint16_t>(worldUpdateSizeAt,(uint16_t)(outp.size() - (worldUpdateSizeAt + 2)));
  424. outp.armor(peer->key(),true,peer->aesKeysIfSupported());
  425. peer->recordOutgoingPacket(_path,outp.packetId(),outp.payloadLength(),outp.verb(),ZT_QOS_NO_FLOW,now);
  426. _path->send(RR,tPtr,outp.data(),outp.size(),now);
  427. peer->setRemoteVersion(protoVersion,vMajor,vMinor,vRevision); // important for this to go first so received() knows the version
  428. peer->received(tPtr,_path,hops(),pid,payloadLength(),Packet::VERB_HELLO,0,Packet::VERB_NOP,false,0,ZT_QOS_NO_FLOW);
  429. return true;
  430. }
  431. bool IncomingPacket::_doOK(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  432. {
  433. const Packet::Verb inReVerb = (Packet::Verb)(*this)[ZT_PROTO_VERB_OK_IDX_IN_RE_VERB];
  434. const uint64_t inRePacketId = at<uint64_t>(ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID);
  435. uint64_t networkId = 0;
  436. if (!RR->node->expectingReplyTo(inRePacketId))
  437. return true;
  438. switch(inReVerb) {
  439. case Packet::VERB_HELLO: {
  440. const uint64_t latency = RR->node->now() - at<uint64_t>(ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP);
  441. const unsigned int vProto = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION];
  442. const unsigned int vMajor = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION];
  443. const unsigned int vMinor = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION];
  444. const unsigned int vRevision = at<uint16_t>(ZT_PROTO_VERB_HELLO__OK__IDX_REVISION);
  445. if (vProto < ZT_PROTO_VERSION_MIN)
  446. return true;
  447. InetAddress externalSurfaceAddress;
  448. unsigned int ptr = ZT_PROTO_VERB_HELLO__OK__IDX_REVISION + 2;
  449. // Get reported external surface address if present
  450. if (ptr < size())
  451. ptr += externalSurfaceAddress.deserialize(*this,ptr);
  452. // Handle planet or moon updates if present
  453. if ((ptr + 2) <= size()) {
  454. const unsigned int worldsLen = at<uint16_t>(ptr); ptr += 2;
  455. if (RR->topology->shouldAcceptWorldUpdateFrom(peer->address())) {
  456. const unsigned int endOfWorlds = ptr + worldsLen;
  457. while (ptr < endOfWorlds) {
  458. World w;
  459. ptr += w.deserialize(*this,ptr);
  460. RR->topology->addWorld(tPtr,w,false);
  461. }
  462. } else {
  463. ptr += worldsLen;
  464. }
  465. }
  466. if (!hops()) {
  467. SharedPtr<Bond> bond = peer->bond();
  468. if (!bond) {
  469. _path->updateLatency((unsigned int)latency,RR->node->now());
  470. }
  471. }
  472. peer->setRemoteVersion(vProto,vMajor,vMinor,vRevision);
  473. if ((externalSurfaceAddress)&&(hops() == 0))
  474. RR->sa->iam(tPtr,peer->address(),_path->localSocket(),_path->address(),externalSurfaceAddress,RR->topology->isUpstream(peer->identity()),RR->node->now());
  475. } break;
  476. case Packet::VERB_WHOIS:
  477. if (RR->topology->isUpstream(peer->identity())) {
  478. const Identity id(*this,ZT_PROTO_VERB_WHOIS__OK__IDX_IDENTITY);
  479. RR->sw->doAnythingWaitingForPeer(tPtr,RR->topology->addPeer(tPtr,SharedPtr<Peer>(new Peer(RR,RR->identity,id))));
  480. }
  481. break;
  482. case Packet::VERB_NETWORK_CONFIG_REQUEST: {
  483. networkId = at<uint64_t>(ZT_PROTO_VERB_OK_IDX_PAYLOAD);
  484. const SharedPtr<Network> network(RR->node->network(networkId));
  485. if (network)
  486. network->handleConfigChunk(tPtr,packetId(),source(),*this,ZT_PROTO_VERB_OK_IDX_PAYLOAD);
  487. } break;
  488. case Packet::VERB_MULTICAST_GATHER: {
  489. networkId = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID);
  490. const SharedPtr<Network> network(RR->node->network(networkId));
  491. if (network) {
  492. 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));
  493. const unsigned int count = at<uint16_t>(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_GATHER_RESULTS + 4);
  494. 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));
  495. }
  496. } break;
  497. case Packet::VERB_MULTICAST_FRAME: {
  498. const unsigned int flags = (*this)[ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_FLAGS];
  499. networkId = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_NETWORK_ID);
  500. 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));
  501. const SharedPtr<Network> network(RR->node->network(networkId));
  502. if (network) {
  503. unsigned int offset = 0;
  504. if ((flags & 0x01) != 0) { // deprecated but still used by older peers
  505. CertificateOfMembership com;
  506. offset += com.deserialize(*this,ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_COM_AND_GATHER_RESULTS);
  507. if (com)
  508. network->addCredential(tPtr,com);
  509. }
  510. if ((flags & 0x02) != 0) {
  511. // OK(MULTICAST_FRAME) includes implicit gather results
  512. offset += ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_COM_AND_GATHER_RESULTS;
  513. unsigned int totalKnown = at<uint32_t>(offset); offset += 4;
  514. unsigned int count = at<uint16_t>(offset); offset += 2;
  515. RR->mc->addMultiple(tPtr,RR->node->now(),networkId,mg,field(offset,count * 5),count,totalKnown);
  516. }
  517. }
  518. } break;
  519. default: break;
  520. }
  521. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_OK,inRePacketId,inReVerb,false,networkId,ZT_QOS_NO_FLOW);
  522. return true;
  523. }
  524. bool IncomingPacket::_doWHOIS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  525. {
  526. if ((!RR->topology->amUpstream())&&(!peer->rateGateInboundWhoisRequest(RR->node->now())))
  527. return true;
  528. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  529. outp.append((unsigned char)Packet::VERB_WHOIS);
  530. outp.append(packetId());
  531. unsigned int count = 0;
  532. unsigned int ptr = ZT_PACKET_IDX_PAYLOAD;
  533. while ((ptr + ZT_ADDRESS_LENGTH) <= size()) {
  534. const Address addr(field(ptr,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  535. ptr += ZT_ADDRESS_LENGTH;
  536. const Identity id(RR->topology->getIdentity(tPtr,addr));
  537. if (id) {
  538. id.serialize(outp,false);
  539. ++count;
  540. } else {
  541. // Request unknown WHOIS from upstream from us (if we have one)
  542. RR->sw->requestWhois(tPtr,RR->node->now(),addr);
  543. }
  544. }
  545. if (count > 0) {
  546. outp.armor(peer->key(),true,peer->aesKeysIfSupported());
  547. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  548. }
  549. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_WHOIS,0,Packet::VERB_NOP,false,0,ZT_QOS_NO_FLOW);
  550. return true;
  551. }
  552. bool IncomingPacket::_doRENDEZVOUS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  553. {
  554. if (RR->topology->isUpstream(peer->identity())) {
  555. const Address with(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  556. const SharedPtr<Peer> rendezvousWith(RR->topology->getPeer(tPtr,with));
  557. if (rendezvousWith) {
  558. const unsigned int port = at<uint16_t>(ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT);
  559. const unsigned int addrlen = (*this)[ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN];
  560. if ((port > 0)&&((addrlen == 4)||(addrlen == 16))) {
  561. InetAddress atAddr(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS,addrlen),addrlen,port);
  562. if (RR->node->shouldUsePathForZeroTierTraffic(tPtr,with,_path->localSocket(),atAddr)) {
  563. const uint64_t junk = RR->node->prng();
  564. RR->node->putPacket(tPtr,_path->localSocket(),atAddr,&junk,4,2); // send low-TTL junk packet to 'open' local NAT(s) and stateful firewalls
  565. rendezvousWith->attemptToContactAt(tPtr,_path->localSocket(),atAddr,RR->node->now(),false);
  566. }
  567. }
  568. }
  569. }
  570. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_RENDEZVOUS,0,Packet::VERB_NOP,false,0,ZT_QOS_NO_FLOW);
  571. return true;
  572. }
  573. // Returns true if packet appears valid; pos and proto will be set
  574. static bool _ipv6GetPayload(const uint8_t *frameData,unsigned int frameLen,unsigned int &pos,unsigned int &proto)
  575. {
  576. if (frameLen < 40)
  577. return false;
  578. pos = 40;
  579. proto = frameData[6];
  580. while (pos <= frameLen) {
  581. switch(proto) {
  582. case 0: // hop-by-hop options
  583. case 43: // routing
  584. case 60: // destination options
  585. case 135: // mobility options
  586. if ((pos + 8) > frameLen)
  587. return false; // invalid!
  588. proto = frameData[pos];
  589. pos += ((unsigned int)frameData[pos + 1] * 8) + 8;
  590. break;
  591. //case 44: // fragment -- we currently can't parse these and they are deprecated in IPv6 anyway
  592. //case 50:
  593. //case 51: // IPSec ESP and AH -- we have to stop here since this is encrypted stuff
  594. default:
  595. return true;
  596. }
  597. }
  598. return false; // overflow == invalid
  599. }
  600. bool IncomingPacket::_doFRAME(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer,int32_t flowId)
  601. {
  602. int32_t _flowId = ZT_QOS_NO_FLOW;
  603. SharedPtr<Bond> bond = peer->bond();
  604. if (bond && bond->flowHashingEnabled()) {
  605. if (size() > ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD) {
  606. const unsigned int etherType = at<uint16_t>(ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE);
  607. const unsigned int frameLen = size() - ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  608. const uint8_t *const frameData = reinterpret_cast<const uint8_t *>(data()) + ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  609. if (etherType == ZT_ETHERTYPE_IPV4 && (frameLen >= 20)) {
  610. uint16_t srcPort = 0;
  611. uint16_t dstPort = 0;
  612. uint8_t proto = (reinterpret_cast<const uint8_t *>(frameData)[9]);
  613. const unsigned int headerLen = 4 * (reinterpret_cast<const uint8_t *>(frameData)[0] & 0xf);
  614. switch(proto) {
  615. case 0x01: // ICMP
  616. //flowId = 0x01;
  617. break;
  618. // All these start with 16-bit source and destination port in that order
  619. case 0x06: // TCP
  620. case 0x11: // UDP
  621. case 0x84: // SCTP
  622. case 0x88: // UDPLite
  623. if (frameLen > (headerLen + 4)) {
  624. unsigned int pos = headerLen + 0;
  625. srcPort = (reinterpret_cast<const uint8_t *>(frameData)[pos++]) << 8;
  626. srcPort |= (reinterpret_cast<const uint8_t *>(frameData)[pos]);
  627. pos++;
  628. dstPort = (reinterpret_cast<const uint8_t *>(frameData)[pos++]) << 8;
  629. dstPort |= (reinterpret_cast<const uint8_t *>(frameData)[pos]);
  630. _flowId = dstPort ^ srcPort ^ proto;
  631. }
  632. break;
  633. }
  634. }
  635. if (etherType == ZT_ETHERTYPE_IPV6 && (frameLen >= 40)) {
  636. uint16_t srcPort = 0;
  637. uint16_t dstPort = 0;
  638. unsigned int pos;
  639. unsigned int proto;
  640. _ipv6GetPayload((const uint8_t *)frameData, frameLen, pos, proto);
  641. switch(proto) {
  642. case 0x3A: // ICMPv6
  643. //flowId = 0x3A;
  644. break;
  645. // All these start with 16-bit source and destination port in that order
  646. case 0x06: // TCP
  647. case 0x11: // UDP
  648. case 0x84: // SCTP
  649. case 0x88: // UDPLite
  650. if (frameLen > (pos + 4)) {
  651. srcPort = (reinterpret_cast<const uint8_t *>(frameData)[pos++]) << 8;
  652. srcPort |= (reinterpret_cast<const uint8_t *>(frameData)[pos]);
  653. pos++;
  654. dstPort = (reinterpret_cast<const uint8_t *>(frameData)[pos++]) << 8;
  655. dstPort |= (reinterpret_cast<const uint8_t *>(frameData)[pos]);
  656. _flowId = dstPort ^ srcPort ^ proto;
  657. }
  658. break;
  659. default:
  660. break;
  661. }
  662. }
  663. }
  664. }
  665. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID);
  666. const SharedPtr<Network> network(RR->node->network(nwid));
  667. bool trustEstablished = false;
  668. if (network) {
  669. if (network->gate(tPtr,peer)) {
  670. trustEstablished = true;
  671. if (size() > ZT_PROTO_VERB_FRAME_IDX_PAYLOAD) {
  672. const unsigned int etherType = at<uint16_t>(ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE);
  673. const MAC sourceMac(peer->address(),nwid);
  674. const unsigned int frameLen = size() - ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  675. const uint8_t *const frameData = reinterpret_cast<const uint8_t *>(data()) + ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  676. if (network->filterIncomingPacket(tPtr,peer,RR->identity.address(),sourceMac,network->mac(),frameData,frameLen,etherType,0) > 0)
  677. RR->node->putFrame(tPtr,nwid,network->userPtr(),sourceMac,network->mac(),etherType,0,(const void *)frameData,frameLen);
  678. }
  679. } else {
  680. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  681. return false;
  682. }
  683. }
  684. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_FRAME,0,Packet::VERB_NOP,trustEstablished,nwid,_flowId);
  685. return true;
  686. }
  687. bool IncomingPacket::_doEXT_FRAME(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer,int32_t flowId)
  688. {
  689. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID);
  690. const SharedPtr<Network> network(RR->node->network(nwid));
  691. if (network) {
  692. const unsigned int flags = (*this)[ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS];
  693. unsigned int comLen = 0;
  694. if ((flags & 0x01) != 0) { // inline COM with EXT_FRAME is deprecated but still used with old peers
  695. CertificateOfMembership com;
  696. comLen = com.deserialize(*this,ZT_PROTO_VERB_EXT_FRAME_IDX_COM);
  697. if (com)
  698. network->addCredential(tPtr,com);
  699. }
  700. if (!network->gate(tPtr,peer)) {
  701. RR->t->incomingNetworkAccessDenied(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,true);
  702. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  703. return false;
  704. }
  705. if (size() > ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD) {
  706. const unsigned int etherType = at<uint16_t>(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE);
  707. 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);
  708. 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);
  709. const unsigned int frameLen = size() - (comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD);
  710. const uint8_t *const frameData = (const uint8_t *)field(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD,frameLen);
  711. if ((!from)||(from == network->mac())) {
  712. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,true,nwid,flowId); // trustEstablished because COM is okay
  713. return true;
  714. }
  715. switch (network->filterIncomingPacket(tPtr,peer,RR->identity.address(),from,to,frameData,frameLen,etherType,0)) {
  716. case 1:
  717. if (from != MAC(peer->address(),nwid)) {
  718. if (network->config().permitsBridging(peer->address())) {
  719. network->learnBridgeRoute(from,peer->address());
  720. } else {
  721. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,from,to,"bridging not allowed (remote)");
  722. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,true,nwid,flowId); // trustEstablished because COM is okay
  723. return true;
  724. }
  725. } else if (to != network->mac()) {
  726. if (to.isMulticast()) {
  727. if (network->config().multicastLimit == 0) {
  728. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,from,to,"multicast disabled");
  729. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,true,nwid,flowId); // trustEstablished because COM is okay
  730. return true;
  731. }
  732. } else if (!network->config().permitsBridging(RR->identity.address())) {
  733. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,from,to,"bridging not allowed (local)");
  734. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,true,nwid,flowId); // trustEstablished because COM is okay
  735. return true;
  736. }
  737. }
  738. // fall through -- 2 means accept regardless of bridging checks or other restrictions
  739. case 2:
  740. RR->node->putFrame(tPtr,nwid,network->userPtr(),from,to,etherType,0,(const void *)frameData,frameLen);
  741. break;
  742. }
  743. }
  744. if ((flags & 0x10) != 0) { // ACK requested
  745. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  746. outp.append((uint8_t)Packet::VERB_EXT_FRAME);
  747. outp.append((uint64_t)packetId());
  748. outp.append((uint64_t)nwid);
  749. const int64_t now = RR->node->now();
  750. outp.armor(peer->key(),true,peer->aesKeysIfSupported());
  751. peer->recordOutgoingPacket(_path,outp.packetId(),outp.payloadLength(),outp.verb(),ZT_QOS_NO_FLOW,now);
  752. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  753. }
  754. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,true,nwid,flowId);
  755. } else {
  756. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,false,nwid,flowId);
  757. }
  758. return true;
  759. }
  760. bool IncomingPacket::_doECHO(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  761. {
  762. uint64_t now = RR->node->now();
  763. if (!peer->rateGateEchoRequest(now)) {
  764. return true;
  765. }
  766. const uint64_t pid = packetId();
  767. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  768. outp.append((unsigned char)Packet::VERB_ECHO);
  769. outp.append((uint64_t)pid);
  770. if (size() > ZT_PACKET_IDX_PAYLOAD)
  771. outp.append(reinterpret_cast<const unsigned char *>(data()) + ZT_PACKET_IDX_PAYLOAD,size() - ZT_PACKET_IDX_PAYLOAD);
  772. outp.armor(peer->key(),true,peer->aesKeysIfSupported());
  773. peer->recordOutgoingPacket(_path,outp.packetId(),outp.payloadLength(),outp.verb(),ZT_QOS_NO_FLOW,now);
  774. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  775. peer->received(tPtr,_path,hops(),pid,payloadLength(),Packet::VERB_ECHO,0,Packet::VERB_NOP,false,0,ZT_QOS_NO_FLOW);
  776. return true;
  777. }
  778. bool IncomingPacket::_doMULTICAST_LIKE(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  779. {
  780. const int64_t now = RR->node->now();
  781. bool authorized = false;
  782. uint64_t lastNwid = 0;
  783. // Packet contains a series of 18-byte network,MAC,ADI tuples
  784. for(unsigned int ptr=ZT_PACKET_IDX_PAYLOAD;ptr<size();ptr+=18) {
  785. const uint64_t nwid = at<uint64_t>(ptr);
  786. if (nwid != lastNwid) {
  787. lastNwid = nwid;
  788. SharedPtr<Network> network(RR->node->network(nwid));
  789. if (network)
  790. authorized = network->gate(tPtr,peer);
  791. if (!authorized)
  792. authorized = ((RR->topology->amUpstream())||(RR->node->localControllerHasAuthorized(now,nwid,peer->address())));
  793. }
  794. if (authorized)
  795. RR->mc->add(tPtr,now,nwid,MulticastGroup(MAC(field(ptr + 8,6),6),at<uint32_t>(ptr + 14)),peer->address());
  796. }
  797. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_MULTICAST_LIKE,0,Packet::VERB_NOP,false,0,ZT_QOS_NO_FLOW);
  798. return true;
  799. }
  800. bool IncomingPacket::_doNETWORK_CREDENTIALS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  801. {
  802. if (!peer->rateGateCredentialsReceived(RR->node->now()))
  803. return true;
  804. CertificateOfMembership com;
  805. Capability cap;
  806. Tag tag;
  807. Revocation revocation;
  808. CertificateOfOwnership coo;
  809. bool trustEstablished = false;
  810. SharedPtr<Network> network;
  811. unsigned int p = ZT_PACKET_IDX_PAYLOAD;
  812. while ((p < size())&&((*this)[p] != 0)) {
  813. p += com.deserialize(*this,p);
  814. if (com) {
  815. network = RR->node->network(com.networkId());
  816. if (network) {
  817. switch (network->addCredential(tPtr,com)) {
  818. case Membership::ADD_REJECTED:
  819. break;
  820. case Membership::ADD_ACCEPTED_NEW:
  821. case Membership::ADD_ACCEPTED_REDUNDANT:
  822. trustEstablished = true;
  823. break;
  824. case Membership::ADD_DEFERRED_FOR_WHOIS:
  825. return false;
  826. }
  827. }
  828. }
  829. }
  830. ++p; // skip trailing 0 after COMs if present
  831. if (p < size()) { // older ZeroTier versions do not send capabilities, tags, or revocations
  832. const unsigned int numCapabilities = at<uint16_t>(p); p += 2;
  833. for(unsigned int i=0;i<numCapabilities;++i) {
  834. p += cap.deserialize(*this,p);
  835. if ((!network)||(network->id() != cap.networkId()))
  836. network = RR->node->network(cap.networkId());
  837. if (network) {
  838. switch (network->addCredential(tPtr,cap)) {
  839. case Membership::ADD_REJECTED:
  840. break;
  841. case Membership::ADD_ACCEPTED_NEW:
  842. case Membership::ADD_ACCEPTED_REDUNDANT:
  843. trustEstablished = true;
  844. break;
  845. case Membership::ADD_DEFERRED_FOR_WHOIS:
  846. return false;
  847. }
  848. }
  849. }
  850. if (p >= size()) return true;
  851. const unsigned int numTags = at<uint16_t>(p); p += 2;
  852. for(unsigned int i=0;i<numTags;++i) {
  853. p += tag.deserialize(*this,p);
  854. if ((!network)||(network->id() != tag.networkId()))
  855. network = RR->node->network(tag.networkId());
  856. if (network) {
  857. switch (network->addCredential(tPtr,tag)) {
  858. case Membership::ADD_REJECTED:
  859. break;
  860. case Membership::ADD_ACCEPTED_NEW:
  861. case Membership::ADD_ACCEPTED_REDUNDANT:
  862. trustEstablished = true;
  863. break;
  864. case Membership::ADD_DEFERRED_FOR_WHOIS:
  865. return false;
  866. }
  867. }
  868. }
  869. if (p >= size()) return true;
  870. const unsigned int numRevocations = at<uint16_t>(p); p += 2;
  871. for(unsigned int i=0;i<numRevocations;++i) {
  872. p += revocation.deserialize(*this,p);
  873. if ((!network)||(network->id() != revocation.networkId()))
  874. network = RR->node->network(revocation.networkId());
  875. if (network) {
  876. switch(network->addCredential(tPtr,peer->address(),revocation)) {
  877. case Membership::ADD_REJECTED:
  878. break;
  879. case Membership::ADD_ACCEPTED_NEW:
  880. case Membership::ADD_ACCEPTED_REDUNDANT:
  881. trustEstablished = true;
  882. break;
  883. case Membership::ADD_DEFERRED_FOR_WHOIS:
  884. return false;
  885. }
  886. }
  887. }
  888. if (p >= size()) return true;
  889. const unsigned int numCoos = at<uint16_t>(p); p += 2;
  890. for(unsigned int i=0;i<numCoos;++i) {
  891. p += coo.deserialize(*this,p);
  892. if ((!network)||(network->id() != coo.networkId()))
  893. network = RR->node->network(coo.networkId());
  894. if (network) {
  895. switch(network->addCredential(tPtr,coo)) {
  896. case Membership::ADD_REJECTED:
  897. break;
  898. case Membership::ADD_ACCEPTED_NEW:
  899. case Membership::ADD_ACCEPTED_REDUNDANT:
  900. trustEstablished = true;
  901. break;
  902. case Membership::ADD_DEFERRED_FOR_WHOIS:
  903. return false;
  904. }
  905. }
  906. }
  907. }
  908. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_NETWORK_CREDENTIALS,0,Packet::VERB_NOP,trustEstablished,(network) ? network->id() : 0,ZT_QOS_NO_FLOW);
  909. return true;
  910. }
  911. bool IncomingPacket::_doNETWORK_CONFIG_REQUEST(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  912. {
  913. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID);
  914. const unsigned int hopCount = hops();
  915. const uint64_t requestPacketId = packetId();
  916. if (RR->localNetworkController) {
  917. 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;
  918. const char *metaDataBytes = (metaDataLength != 0) ? (const char *)field(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT,metaDataLength) : (const char *)0;
  919. const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> metaData(metaDataBytes,metaDataLength);
  920. RR->localNetworkController->request(nwid,(hopCount > 0) ? InetAddress() : _path->address(),requestPacketId,peer->identity(),metaData);
  921. } else {
  922. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_ERROR);
  923. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  924. outp.append(requestPacketId);
  925. outp.append((unsigned char)Packet::ERROR_UNSUPPORTED_OPERATION);
  926. outp.append(nwid);
  927. outp.armor(peer->key(),true,peer->aesKeysIfSupported());
  928. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  929. }
  930. peer->received(tPtr,_path,hopCount,requestPacketId,payloadLength(),Packet::VERB_NETWORK_CONFIG_REQUEST,0,Packet::VERB_NOP,false,nwid,ZT_QOS_NO_FLOW);
  931. return true;
  932. }
  933. bool IncomingPacket::_doNETWORK_CONFIG(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  934. {
  935. const SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PACKET_IDX_PAYLOAD)));
  936. if (network) {
  937. const uint64_t configUpdateId = network->handleConfigChunk(tPtr,packetId(),source(),*this,ZT_PACKET_IDX_PAYLOAD);
  938. if (configUpdateId) {
  939. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  940. outp.append((uint8_t)Packet::VERB_ECHO);
  941. outp.append((uint64_t)packetId());
  942. outp.append((uint64_t)network->id());
  943. outp.append((uint64_t)configUpdateId);
  944. const int64_t now = RR->node->now();
  945. outp.armor(peer->key(),true,peer->aesKeysIfSupported());
  946. peer->recordOutgoingPacket(_path,outp.packetId(),outp.payloadLength(),outp.verb(),ZT_QOS_NO_FLOW,now);
  947. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  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