IncomingPacket.cpp 55 KB

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