IncomingPacket.cpp 53 KB

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