IncomingPacket.cpp 54 KB

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