IncomingPacket.cpp 54 KB

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