IncomingPacket.cpp 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333
  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. RR->sw->doAnythingWaitingForPeer(tPtr,RR->topology->addPeer(tPtr,SharedPtr<Peer>(new Peer(RR,RR->identity,id))));
  453. }
  454. break;
  455. case Packet::VERB_NETWORK_CONFIG_REQUEST: {
  456. networkId = at<uint64_t>(ZT_PROTO_VERB_OK_IDX_PAYLOAD);
  457. const SharedPtr<Network> network(RR->node->network(networkId));
  458. if (network)
  459. network->handleConfigChunk(tPtr,packetId(),source(),*this,ZT_PROTO_VERB_OK_IDX_PAYLOAD);
  460. } break;
  461. case Packet::VERB_MULTICAST_GATHER: {
  462. networkId = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID);
  463. const SharedPtr<Network> network(RR->node->network(networkId));
  464. if (network) {
  465. 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));
  466. const unsigned int count = at<uint16_t>(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_GATHER_RESULTS + 4);
  467. 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));
  468. }
  469. } break;
  470. case Packet::VERB_MULTICAST_FRAME: {
  471. const unsigned int flags = (*this)[ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_FLAGS];
  472. networkId = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_NETWORK_ID);
  473. 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));
  474. const SharedPtr<Network> network(RR->node->network(networkId));
  475. if (network) {
  476. unsigned int offset = 0;
  477. if ((flags & 0x01) != 0) { // deprecated but still used by older peers
  478. CertificateOfMembership com;
  479. offset += com.deserialize(*this,ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_COM_AND_GATHER_RESULTS);
  480. if (com)
  481. network->addCredential(tPtr,com);
  482. }
  483. if ((flags & 0x02) != 0) {
  484. // OK(MULTICAST_FRAME) includes implicit gather results
  485. offset += ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_COM_AND_GATHER_RESULTS;
  486. unsigned int totalKnown = at<uint32_t>(offset); offset += 4;
  487. unsigned int count = at<uint16_t>(offset); offset += 2;
  488. RR->mc->addMultiple(tPtr,RR->node->now(),networkId,mg,field(offset,count * 5),count,totalKnown);
  489. }
  490. }
  491. } break;
  492. default: break;
  493. }
  494. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_OK,inRePacketId,inReVerb,false,networkId,ZT_QOS_NO_FLOW);
  495. return true;
  496. }
  497. bool IncomingPacket::_doWHOIS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  498. {
  499. if ((!RR->topology->amUpstream())&&(!peer->rateGateInboundWhoisRequest(RR->node->now())))
  500. return true;
  501. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  502. outp.append((unsigned char)Packet::VERB_WHOIS);
  503. outp.append(packetId());
  504. unsigned int count = 0;
  505. unsigned int ptr = ZT_PACKET_IDX_PAYLOAD;
  506. while ((ptr + ZT_ADDRESS_LENGTH) <= size()) {
  507. const Address addr(field(ptr,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  508. ptr += ZT_ADDRESS_LENGTH;
  509. const Identity id(RR->topology->getIdentity(tPtr,addr));
  510. if (id) {
  511. id.serialize(outp,false);
  512. ++count;
  513. } else {
  514. // Request unknown WHOIS from upstream from us (if we have one)
  515. RR->sw->requestWhois(tPtr,RR->node->now(),addr);
  516. }
  517. }
  518. if (count > 0) {
  519. outp.armor(peer->key(),true,peer->aesKeysIfSupported());
  520. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  521. }
  522. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_WHOIS,0,Packet::VERB_NOP,false,0,ZT_QOS_NO_FLOW);
  523. return true;
  524. }
  525. bool IncomingPacket::_doRENDEZVOUS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  526. {
  527. if (RR->topology->isUpstream(peer->identity())) {
  528. const Address with(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  529. const SharedPtr<Peer> rendezvousWith(RR->topology->getPeer(tPtr,with));
  530. if (rendezvousWith) {
  531. const unsigned int port = at<uint16_t>(ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT);
  532. const unsigned int addrlen = (*this)[ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN];
  533. if ((port > 0)&&((addrlen == 4)||(addrlen == 16))) {
  534. InetAddress atAddr(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS,addrlen),addrlen,port);
  535. if (RR->node->shouldUsePathForZeroTierTraffic(tPtr,with,_path->localSocket(),atAddr)) {
  536. const uint64_t junk = RR->node->prng();
  537. RR->node->putPacket(tPtr,_path->localSocket(),atAddr,&junk,4,2); // send low-TTL junk packet to 'open' local NAT(s) and stateful firewalls
  538. rendezvousWith->attemptToContactAt(tPtr,_path->localSocket(),atAddr,RR->node->now(),false);
  539. }
  540. }
  541. }
  542. }
  543. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_RENDEZVOUS,0,Packet::VERB_NOP,false,0,ZT_QOS_NO_FLOW);
  544. return true;
  545. }
  546. // Returns true if packet appears valid; pos and proto will be set
  547. static bool _ipv6GetPayload(const uint8_t *frameData,unsigned int frameLen,unsigned int &pos,unsigned int &proto)
  548. {
  549. if (frameLen < 40)
  550. return false;
  551. pos = 40;
  552. proto = frameData[6];
  553. while (pos <= frameLen) {
  554. switch(proto) {
  555. case 0: // hop-by-hop options
  556. case 43: // routing
  557. case 60: // destination options
  558. case 135: // mobility options
  559. if ((pos + 8) > frameLen)
  560. return false; // invalid!
  561. proto = frameData[pos];
  562. pos += ((unsigned int)frameData[pos + 1] * 8) + 8;
  563. break;
  564. //case 44: // fragment -- we currently can't parse these and they are deprecated in IPv6 anyway
  565. //case 50:
  566. //case 51: // IPSec ESP and AH -- we have to stop here since this is encrypted stuff
  567. default:
  568. return true;
  569. }
  570. }
  571. return false; // overflow == invalid
  572. }
  573. bool IncomingPacket::_doFRAME(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer,int32_t flowId)
  574. {
  575. int32_t _flowId = ZT_QOS_NO_FLOW;
  576. SharedPtr<Bond> bond = peer->bond();
  577. if (bond && bond->flowHashingEnabled()) {
  578. if (size() > ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD) {
  579. const unsigned int etherType = at<uint16_t>(ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE);
  580. const unsigned int frameLen = size() - ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  581. const uint8_t *const frameData = reinterpret_cast<const uint8_t *>(data()) + ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  582. if (etherType == ZT_ETHERTYPE_IPV4 && (frameLen >= 20)) {
  583. uint16_t srcPort = 0;
  584. uint16_t dstPort = 0;
  585. uint8_t proto = (reinterpret_cast<const uint8_t *>(frameData)[9]);
  586. const unsigned int headerLen = 4 * (reinterpret_cast<const uint8_t *>(frameData)[0] & 0xf);
  587. switch(proto) {
  588. case 0x01: // ICMP
  589. //flowId = 0x01;
  590. break;
  591. // All these start with 16-bit source and destination port in that order
  592. case 0x06: // TCP
  593. case 0x11: // UDP
  594. case 0x84: // SCTP
  595. case 0x88: // UDPLite
  596. if (frameLen > (headerLen + 4)) {
  597. unsigned int pos = headerLen + 0;
  598. srcPort = (reinterpret_cast<const uint8_t *>(frameData)[pos++]) << 8;
  599. srcPort |= (reinterpret_cast<const uint8_t *>(frameData)[pos]);
  600. pos++;
  601. dstPort = (reinterpret_cast<const uint8_t *>(frameData)[pos++]) << 8;
  602. dstPort |= (reinterpret_cast<const uint8_t *>(frameData)[pos]);
  603. _flowId = dstPort ^ srcPort ^ proto;
  604. }
  605. break;
  606. }
  607. }
  608. if (etherType == ZT_ETHERTYPE_IPV6 && (frameLen >= 40)) {
  609. uint16_t srcPort = 0;
  610. uint16_t dstPort = 0;
  611. unsigned int pos;
  612. unsigned int proto;
  613. _ipv6GetPayload((const uint8_t *)frameData, frameLen, pos, proto);
  614. switch(proto) {
  615. case 0x3A: // ICMPv6
  616. //flowId = 0x3A;
  617. break;
  618. // All these start with 16-bit source and destination port in that order
  619. case 0x06: // TCP
  620. case 0x11: // UDP
  621. case 0x84: // SCTP
  622. case 0x88: // UDPLite
  623. if (frameLen > (pos + 4)) {
  624. srcPort = (reinterpret_cast<const uint8_t *>(frameData)[pos++]) << 8;
  625. srcPort |= (reinterpret_cast<const uint8_t *>(frameData)[pos]);
  626. pos++;
  627. dstPort = (reinterpret_cast<const uint8_t *>(frameData)[pos++]) << 8;
  628. dstPort |= (reinterpret_cast<const uint8_t *>(frameData)[pos]);
  629. _flowId = dstPort ^ srcPort ^ proto;
  630. }
  631. break;
  632. default:
  633. break;
  634. }
  635. }
  636. }
  637. }
  638. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID);
  639. const SharedPtr<Network> network(RR->node->network(nwid));
  640. bool trustEstablished = false;
  641. if (network) {
  642. if (network->gate(tPtr,peer)) {
  643. trustEstablished = true;
  644. if (size() > ZT_PROTO_VERB_FRAME_IDX_PAYLOAD) {
  645. const unsigned int etherType = at<uint16_t>(ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE);
  646. const MAC sourceMac(peer->address(),nwid);
  647. const unsigned int frameLen = size() - ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  648. const uint8_t *const frameData = reinterpret_cast<const uint8_t *>(data()) + ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  649. if (network->filterIncomingPacket(tPtr,peer,RR->identity.address(),sourceMac,network->mac(),frameData,frameLen,etherType,0) > 0)
  650. RR->node->putFrame(tPtr,nwid,network->userPtr(),sourceMac,network->mac(),etherType,0,(const void *)frameData,frameLen);
  651. }
  652. } else {
  653. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  654. return false;
  655. }
  656. }
  657. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_FRAME,0,Packet::VERB_NOP,trustEstablished,nwid,_flowId);
  658. return true;
  659. }
  660. bool IncomingPacket::_doEXT_FRAME(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer,int32_t flowId)
  661. {
  662. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID);
  663. const SharedPtr<Network> network(RR->node->network(nwid));
  664. if (network) {
  665. const unsigned int flags = (*this)[ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS];
  666. unsigned int comLen = 0;
  667. if ((flags & 0x01) != 0) { // inline COM with EXT_FRAME is deprecated but still used with old peers
  668. CertificateOfMembership com;
  669. comLen = com.deserialize(*this,ZT_PROTO_VERB_EXT_FRAME_IDX_COM);
  670. if (com)
  671. network->addCredential(tPtr,com);
  672. }
  673. if (!network->gate(tPtr,peer)) {
  674. RR->t->incomingNetworkAccessDenied(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,true);
  675. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  676. return false;
  677. }
  678. if (size() > ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD) {
  679. const unsigned int etherType = at<uint16_t>(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE);
  680. 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);
  681. 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);
  682. const unsigned int frameLen = size() - (comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD);
  683. const uint8_t *const frameData = (const uint8_t *)field(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD,frameLen);
  684. if ((!from)||(from == network->mac())) {
  685. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,true,nwid,flowId); // trustEstablished because COM is okay
  686. return true;
  687. }
  688. switch (network->filterIncomingPacket(tPtr,peer,RR->identity.address(),from,to,frameData,frameLen,etherType,0)) {
  689. case 1:
  690. if (from != MAC(peer->address(),nwid)) {
  691. if (network->config().permitsBridging(peer->address())) {
  692. network->learnBridgeRoute(from,peer->address());
  693. } else {
  694. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,from,to,"bridging not allowed (remote)");
  695. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,true,nwid,flowId); // trustEstablished because COM is okay
  696. return true;
  697. }
  698. } else if (to != network->mac()) {
  699. if (to.isMulticast()) {
  700. if (network->config().multicastLimit == 0) {
  701. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,from,to,"multicast disabled");
  702. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,true,nwid,flowId); // trustEstablished because COM is okay
  703. return true;
  704. }
  705. } else if (!network->config().permitsBridging(RR->identity.address())) {
  706. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,from,to,"bridging not allowed (local)");
  707. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,true,nwid,flowId); // trustEstablished because COM is okay
  708. return true;
  709. }
  710. }
  711. // fall through -- 2 means accept regardless of bridging checks or other restrictions
  712. case 2:
  713. RR->node->putFrame(tPtr,nwid,network->userPtr(),from,to,etherType,0,(const void *)frameData,frameLen);
  714. break;
  715. }
  716. }
  717. if ((flags & 0x10) != 0) { // ACK requested
  718. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  719. outp.append((uint8_t)Packet::VERB_EXT_FRAME);
  720. outp.append((uint64_t)packetId());
  721. outp.append((uint64_t)nwid);
  722. const int64_t now = RR->node->now();
  723. outp.armor(peer->key(),true,peer->aesKeysIfSupported());
  724. peer->recordOutgoingPacket(_path,outp.packetId(),outp.payloadLength(),outp.verb(),ZT_QOS_NO_FLOW,now);
  725. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  726. }
  727. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,true,nwid,flowId);
  728. } else {
  729. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,false,nwid,flowId);
  730. }
  731. return true;
  732. }
  733. bool IncomingPacket::_doECHO(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  734. {
  735. uint64_t now = RR->node->now();
  736. if (!peer->rateGateEchoRequest(now)) {
  737. return true;
  738. }
  739. const uint64_t pid = packetId();
  740. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  741. outp.append((unsigned char)Packet::VERB_ECHO);
  742. outp.append((uint64_t)pid);
  743. if (size() > ZT_PACKET_IDX_PAYLOAD)
  744. outp.append(reinterpret_cast<const unsigned char *>(data()) + ZT_PACKET_IDX_PAYLOAD,size() - ZT_PACKET_IDX_PAYLOAD);
  745. outp.armor(peer->key(),true,peer->aesKeysIfSupported());
  746. peer->recordOutgoingPacket(_path,outp.packetId(),outp.payloadLength(),outp.verb(),ZT_QOS_NO_FLOW,now);
  747. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  748. peer->received(tPtr,_path,hops(),pid,payloadLength(),Packet::VERB_ECHO,0,Packet::VERB_NOP,false,0,ZT_QOS_NO_FLOW);
  749. return true;
  750. }
  751. bool IncomingPacket::_doMULTICAST_LIKE(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  752. {
  753. const int64_t now = RR->node->now();
  754. bool authorized = false;
  755. uint64_t lastNwid = 0;
  756. // Packet contains a series of 18-byte network,MAC,ADI tuples
  757. for(unsigned int ptr=ZT_PACKET_IDX_PAYLOAD;ptr<size();ptr+=18) {
  758. const uint64_t nwid = at<uint64_t>(ptr);
  759. if (nwid != lastNwid) {
  760. lastNwid = nwid;
  761. SharedPtr<Network> network(RR->node->network(nwid));
  762. if (network)
  763. authorized = network->gate(tPtr,peer);
  764. if (!authorized)
  765. authorized = ((RR->topology->amUpstream())||(RR->node->localControllerHasAuthorized(now,nwid,peer->address())));
  766. }
  767. if (authorized)
  768. RR->mc->add(tPtr,now,nwid,MulticastGroup(MAC(field(ptr + 8,6),6),at<uint32_t>(ptr + 14)),peer->address());
  769. }
  770. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_MULTICAST_LIKE,0,Packet::VERB_NOP,false,0,ZT_QOS_NO_FLOW);
  771. return true;
  772. }
  773. bool IncomingPacket::_doNETWORK_CREDENTIALS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  774. {
  775. if (!peer->rateGateCredentialsReceived(RR->node->now()))
  776. return true;
  777. CertificateOfMembership com;
  778. Capability cap;
  779. Tag tag;
  780. Revocation revocation;
  781. CertificateOfOwnership coo;
  782. bool trustEstablished = false;
  783. SharedPtr<Network> network;
  784. unsigned int p = ZT_PACKET_IDX_PAYLOAD;
  785. while ((p < size())&&((*this)[p] != 0)) {
  786. p += com.deserialize(*this,p);
  787. if (com) {
  788. network = RR->node->network(com.networkId());
  789. if (network) {
  790. switch (network->addCredential(tPtr,com)) {
  791. case Membership::ADD_REJECTED:
  792. break;
  793. case Membership::ADD_ACCEPTED_NEW:
  794. case Membership::ADD_ACCEPTED_REDUNDANT:
  795. trustEstablished = true;
  796. break;
  797. case Membership::ADD_DEFERRED_FOR_WHOIS:
  798. return false;
  799. }
  800. }
  801. }
  802. }
  803. ++p; // skip trailing 0 after COMs if present
  804. if (p < size()) { // older ZeroTier versions do not send capabilities, tags, or revocations
  805. const unsigned int numCapabilities = at<uint16_t>(p); p += 2;
  806. for(unsigned int i=0;i<numCapabilities;++i) {
  807. p += cap.deserialize(*this,p);
  808. if ((!network)||(network->id() != cap.networkId()))
  809. network = RR->node->network(cap.networkId());
  810. if (network) {
  811. switch (network->addCredential(tPtr,cap)) {
  812. case Membership::ADD_REJECTED:
  813. break;
  814. case Membership::ADD_ACCEPTED_NEW:
  815. case Membership::ADD_ACCEPTED_REDUNDANT:
  816. trustEstablished = true;
  817. break;
  818. case Membership::ADD_DEFERRED_FOR_WHOIS:
  819. return false;
  820. }
  821. }
  822. }
  823. if (p >= size()) return true;
  824. const unsigned int numTags = at<uint16_t>(p); p += 2;
  825. for(unsigned int i=0;i<numTags;++i) {
  826. p += tag.deserialize(*this,p);
  827. if ((!network)||(network->id() != tag.networkId()))
  828. network = RR->node->network(tag.networkId());
  829. if (network) {
  830. switch (network->addCredential(tPtr,tag)) {
  831. case Membership::ADD_REJECTED:
  832. break;
  833. case Membership::ADD_ACCEPTED_NEW:
  834. case Membership::ADD_ACCEPTED_REDUNDANT:
  835. trustEstablished = true;
  836. break;
  837. case Membership::ADD_DEFERRED_FOR_WHOIS:
  838. return false;
  839. }
  840. }
  841. }
  842. if (p >= size()) return true;
  843. const unsigned int numRevocations = at<uint16_t>(p); p += 2;
  844. for(unsigned int i=0;i<numRevocations;++i) {
  845. p += revocation.deserialize(*this,p);
  846. if ((!network)||(network->id() != revocation.networkId()))
  847. network = RR->node->network(revocation.networkId());
  848. if (network) {
  849. switch(network->addCredential(tPtr,peer->address(),revocation)) {
  850. case Membership::ADD_REJECTED:
  851. break;
  852. case Membership::ADD_ACCEPTED_NEW:
  853. case Membership::ADD_ACCEPTED_REDUNDANT:
  854. trustEstablished = true;
  855. break;
  856. case Membership::ADD_DEFERRED_FOR_WHOIS:
  857. return false;
  858. }
  859. }
  860. }
  861. if (p >= size()) return true;
  862. const unsigned int numCoos = at<uint16_t>(p); p += 2;
  863. for(unsigned int i=0;i<numCoos;++i) {
  864. p += coo.deserialize(*this,p);
  865. if ((!network)||(network->id() != coo.networkId()))
  866. network = RR->node->network(coo.networkId());
  867. if (network) {
  868. switch(network->addCredential(tPtr,coo)) {
  869. case Membership::ADD_REJECTED:
  870. break;
  871. case Membership::ADD_ACCEPTED_NEW:
  872. case Membership::ADD_ACCEPTED_REDUNDANT:
  873. trustEstablished = true;
  874. break;
  875. case Membership::ADD_DEFERRED_FOR_WHOIS:
  876. return false;
  877. }
  878. }
  879. }
  880. }
  881. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_NETWORK_CREDENTIALS,0,Packet::VERB_NOP,trustEstablished,(network) ? network->id() : 0,ZT_QOS_NO_FLOW);
  882. return true;
  883. }
  884. bool IncomingPacket::_doNETWORK_CONFIG_REQUEST(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  885. {
  886. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID);
  887. const unsigned int hopCount = hops();
  888. const uint64_t requestPacketId = packetId();
  889. if (RR->localNetworkController) {
  890. 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;
  891. const char *metaDataBytes = (metaDataLength != 0) ? (const char *)field(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT,metaDataLength) : (const char *)0;
  892. const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> metaData(metaDataBytes,metaDataLength);
  893. RR->localNetworkController->request(nwid,(hopCount > 0) ? InetAddress() : _path->address(),requestPacketId,peer->identity(),metaData);
  894. } else {
  895. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_ERROR);
  896. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  897. outp.append(requestPacketId);
  898. outp.append((unsigned char)Packet::ERROR_UNSUPPORTED_OPERATION);
  899. outp.append(nwid);
  900. outp.armor(peer->key(),true,peer->aesKeysIfSupported());
  901. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  902. }
  903. peer->received(tPtr,_path,hopCount,requestPacketId,payloadLength(),Packet::VERB_NETWORK_CONFIG_REQUEST,0,Packet::VERB_NOP,false,nwid,ZT_QOS_NO_FLOW);
  904. return true;
  905. }
  906. bool IncomingPacket::_doNETWORK_CONFIG(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  907. {
  908. const SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PACKET_IDX_PAYLOAD)));
  909. if (network) {
  910. const uint64_t configUpdateId = network->handleConfigChunk(tPtr,packetId(),source(),*this,ZT_PACKET_IDX_PAYLOAD);
  911. if (configUpdateId) {
  912. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  913. outp.append((uint8_t)Packet::VERB_ECHO);
  914. outp.append((uint64_t)packetId());
  915. outp.append((uint64_t)network->id());
  916. outp.append((uint64_t)configUpdateId);
  917. const int64_t now = RR->node->now();
  918. outp.armor(peer->key(),true,peer->aesKeysIfSupported());
  919. peer->recordOutgoingPacket(_path,outp.packetId(),outp.payloadLength(),outp.verb(),ZT_QOS_NO_FLOW,now);
  920. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  921. }
  922. }
  923. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_NETWORK_CONFIG,0,Packet::VERB_NOP,false,(network) ? network->id() : 0,ZT_QOS_NO_FLOW);
  924. return true;
  925. }
  926. bool IncomingPacket::_doMULTICAST_GATHER(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  927. {
  928. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID);
  929. const unsigned int flags = (*this)[ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS];
  930. const MulticastGroup mg(MAC(field(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC,6),6),at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI));
  931. const unsigned int gatherLimit = at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_GATHER_LIMIT);
  932. const SharedPtr<Network> network(RR->node->network(nwid));
  933. if ((flags & 0x01) != 0) {
  934. try {
  935. CertificateOfMembership com;
  936. com.deserialize(*this,ZT_PROTO_VERB_MULTICAST_GATHER_IDX_COM);
  937. if ((com)&&(network))
  938. network->addCredential(tPtr,com);
  939. } catch ( ... ) {} // discard invalid COMs
  940. }
  941. bool trustEstablished = false;
  942. if (network) {
  943. if (network->gate(tPtr,peer)) {
  944. trustEstablished = true;
  945. } else {
  946. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  947. return false;
  948. }
  949. }
  950. const int64_t now = RR->node->now();
  951. if ((gatherLimit > 0)&&((trustEstablished)||(RR->topology->amUpstream())||(RR->node->localControllerHasAuthorized(now,nwid,peer->address())))) {
  952. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  953. outp.append((unsigned char)Packet::VERB_MULTICAST_GATHER);
  954. outp.append(packetId());
  955. outp.append(nwid);
  956. mg.mac().appendTo(outp);
  957. outp.append((uint32_t)mg.adi());
  958. const unsigned int gatheredLocally = RR->mc->gather(peer->address(),nwid,mg,outp,gatherLimit);
  959. if (gatheredLocally > 0) {
  960. outp.armor(peer->key(),true,peer->aesKeysIfSupported());
  961. peer->recordOutgoingPacket(_path,outp.packetId(),outp.payloadLength(),outp.verb(),ZT_QOS_NO_FLOW,now);
  962. _path->send(RR,tPtr,outp.data(),outp.size(),now);
  963. }
  964. }
  965. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_MULTICAST_GATHER,0,Packet::VERB_NOP,trustEstablished,nwid,ZT_QOS_NO_FLOW);
  966. return true;
  967. }
  968. bool IncomingPacket::_doMULTICAST_FRAME(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  969. {
  970. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID);
  971. const unsigned int flags = (*this)[ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS];
  972. const SharedPtr<Network> network(RR->node->network(nwid));
  973. if (network) {
  974. // Offset -- size of optional fields added to position of later fields
  975. unsigned int offset = 0;
  976. if ((flags & 0x01) != 0) {
  977. // This is deprecated but may still be sent by old peers
  978. CertificateOfMembership com;
  979. offset += com.deserialize(*this,ZT_PROTO_VERB_MULTICAST_FRAME_IDX_COM);
  980. if (com)
  981. network->addCredential(tPtr,com);
  982. }
  983. if (!network->gate(tPtr,peer)) {
  984. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  985. return false;
  986. }
  987. unsigned int gatherLimit = 0;
  988. if ((flags & 0x02) != 0) {
  989. gatherLimit = at<uint32_t>(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_GATHER_LIMIT);
  990. offset += 4;
  991. }
  992. MAC from;
  993. if ((flags & 0x04) != 0) {
  994. from.setTo(field(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SOURCE_MAC,6),6);
  995. offset += 6;
  996. } else {
  997. from.fromAddress(peer->address(),nwid);
  998. }
  999. 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));
  1000. const unsigned int etherType = at<uint16_t>(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE);
  1001. const unsigned int frameLen = size() - (offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME);
  1002. if (network->config().multicastLimit == 0) {
  1003. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_MULTICAST_FRAME,from,to.mac(),"multicast disabled");
  1004. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,false,nwid,ZT_QOS_NO_FLOW);
  1005. return true;
  1006. }
  1007. if ((frameLen > 0)&&(frameLen <= ZT_MAX_MTU)) {
  1008. if (!to.mac().isMulticast()) {
  1009. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),source(),hops(),Packet::VERB_MULTICAST_FRAME,"destination not multicast");
  1010. 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
  1011. return true;
  1012. }
  1013. if ((!from)||(from.isMulticast())||(from == network->mac())) {
  1014. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),source(),hops(),Packet::VERB_MULTICAST_FRAME,"invalid source MAC");
  1015. 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
  1016. return true;
  1017. }
  1018. const uint8_t *const frameData = (const uint8_t *)field(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME,frameLen);
  1019. if ((flags & 0x08)&&(network->config().isMulticastReplicator(RR->identity.address())))
  1020. RR->mc->send(tPtr,RR->node->now(),network,peer->address(),to,from,etherType,frameData,frameLen);
  1021. if (from != MAC(peer->address(),nwid)) {
  1022. if (network->config().permitsBridging(peer->address())) {
  1023. network->learnBridgeRoute(from,peer->address());
  1024. } else {
  1025. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_MULTICAST_FRAME,from,to.mac(),"bridging not allowed (remote)");
  1026. 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
  1027. return true;
  1028. }
  1029. }
  1030. if (network->filterIncomingPacket(tPtr,peer,RR->identity.address(),from,to.mac(),frameData,frameLen,etherType,0) > 0)
  1031. RR->node->putFrame(tPtr,nwid,network->userPtr(),from,to.mac(),etherType,0,(const void *)frameData,frameLen);
  1032. }
  1033. if (gatherLimit) {
  1034. Packet outp(source(),RR->identity.address(),Packet::VERB_OK);
  1035. outp.append((unsigned char)Packet::VERB_MULTICAST_FRAME);
  1036. outp.append(packetId());
  1037. outp.append(nwid);
  1038. to.mac().appendTo(outp);
  1039. outp.append((uint32_t)to.adi());
  1040. outp.append((unsigned char)0x02); // flag 0x02 = contains gather results
  1041. if (RR->mc->gather(peer->address(),nwid,to,outp,gatherLimit)) {
  1042. const int64_t now = RR->node->now();
  1043. outp.armor(peer->key(),true,peer->aesKeysIfSupported());
  1044. peer->recordOutgoingPacket(_path,outp.packetId(),outp.payloadLength(),outp.verb(),ZT_QOS_NO_FLOW,now);
  1045. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  1046. }
  1047. }
  1048. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,true,nwid,ZT_QOS_NO_FLOW);
  1049. } else {
  1050. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  1051. return false;
  1052. }
  1053. return true;
  1054. }
  1055. bool IncomingPacket::_doPUSH_DIRECT_PATHS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  1056. {
  1057. const int64_t now = RR->node->now();
  1058. if (!peer->rateGatePushDirectPaths(now)) {
  1059. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_PUSH_DIRECT_PATHS,0,Packet::VERB_NOP,false,0,ZT_QOS_NO_FLOW);
  1060. return true;
  1061. }
  1062. // Second, limit addresses by scope and type
  1063. uint8_t countPerScope[ZT_INETADDRESS_MAX_SCOPE+1][2]; // [][0] is v4, [][1] is v6
  1064. memset(countPerScope,0,sizeof(countPerScope));
  1065. unsigned int count = at<uint16_t>(ZT_PACKET_IDX_PAYLOAD);
  1066. unsigned int ptr = ZT_PACKET_IDX_PAYLOAD + 2;
  1067. while (count--) { // if ptr overflows Buffer will throw
  1068. unsigned int flags = (*this)[ptr++];
  1069. unsigned int extLen = at<uint16_t>(ptr); ptr += 2;
  1070. ptr += extLen; // unused right now
  1071. unsigned int addrType = (*this)[ptr++];
  1072. unsigned int addrLen = (*this)[ptr++];
  1073. switch(addrType) {
  1074. case 4: {
  1075. const InetAddress a(field(ptr,4),4,at<uint16_t>(ptr + 4));
  1076. if (
  1077. ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_FORGET_PATH) == 0) && // not being told to forget
  1078. (!( ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT) == 0) && (peer->hasActivePathTo(now,a)) )) && // not already known
  1079. (RR->node->shouldUsePathForZeroTierTraffic(tPtr,peer->address(),_path->localSocket(),a)) ) // should use path
  1080. {
  1081. if ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT) != 0) {
  1082. peer->clusterRedirect(tPtr,_path,a,now);
  1083. } else if (++countPerScope[(int)a.ipScope()][0] <= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY) {
  1084. peer->attemptToContactAt(tPtr,InetAddress(),a,now,false);
  1085. }
  1086. }
  1087. } break;
  1088. case 6: {
  1089. const InetAddress a(field(ptr,16),16,at<uint16_t>(ptr + 16));
  1090. if (
  1091. ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_FORGET_PATH) == 0) && // not being told to forget
  1092. (!( ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT) == 0) && (peer->hasActivePathTo(now,a)) )) && // not already known
  1093. (RR->node->shouldUsePathForZeroTierTraffic(tPtr,peer->address(),_path->localSocket(),a)) ) // should use path
  1094. {
  1095. if ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT) != 0) {
  1096. peer->clusterRedirect(tPtr,_path,a,now);
  1097. } else if (++countPerScope[(int)a.ipScope()][1] <= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY) {
  1098. peer->attemptToContactAt(tPtr,InetAddress(),a,now,false);
  1099. }
  1100. }
  1101. } break;
  1102. }
  1103. ptr += addrLen;
  1104. }
  1105. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_PUSH_DIRECT_PATHS,0,Packet::VERB_NOP,false,0,ZT_QOS_NO_FLOW);
  1106. return true;
  1107. }
  1108. bool IncomingPacket::_doUSER_MESSAGE(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  1109. {
  1110. if (likely(size() >= (ZT_PACKET_IDX_PAYLOAD + 8))) {
  1111. ZT_UserMessage um;
  1112. um.origin = peer->address().toInt();
  1113. um.typeId = at<uint64_t>(ZT_PACKET_IDX_PAYLOAD);
  1114. um.data = reinterpret_cast<const void *>(reinterpret_cast<const uint8_t *>(data()) + ZT_PACKET_IDX_PAYLOAD + 8);
  1115. um.length = size() - (ZT_PACKET_IDX_PAYLOAD + 8);
  1116. RR->node->postEvent(tPtr,ZT_EVENT_USER_MESSAGE,reinterpret_cast<const void *>(&um));
  1117. }
  1118. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_USER_MESSAGE,0,Packet::VERB_NOP,false,0,ZT_QOS_NO_FLOW);
  1119. return true;
  1120. }
  1121. bool IncomingPacket::_doREMOTE_TRACE(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  1122. {
  1123. ZT_RemoteTrace rt;
  1124. const char *ptr = reinterpret_cast<const char *>(data()) + ZT_PACKET_IDX_PAYLOAD;
  1125. const char *const eof = reinterpret_cast<const char *>(data()) + size();
  1126. rt.origin = peer->address().toInt();
  1127. rt.data = const_cast<char *>(ptr); // start of first string
  1128. while (ptr < eof) {
  1129. if (!*ptr) { // end of string
  1130. rt.len = (unsigned int)(ptr - rt.data);
  1131. if ((rt.len > 0)&&(rt.len <= ZT_MAX_REMOTE_TRACE_SIZE)) {
  1132. RR->node->postEvent(tPtr,ZT_EVENT_REMOTE_TRACE,&rt);
  1133. }
  1134. rt.data = const_cast<char *>(++ptr); // start of next string, if any
  1135. } else {
  1136. ++ptr;
  1137. }
  1138. }
  1139. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_REMOTE_TRACE,0,Packet::VERB_NOP,false,0,ZT_QOS_NO_FLOW);
  1140. return true;
  1141. }
  1142. bool IncomingPacket::_doPATH_NEGOTIATION_REQUEST(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  1143. {
  1144. uint64_t now = RR->node->now();
  1145. SharedPtr<Bond> bond = peer->bond();
  1146. if (!bond || !bond->rateGatePathNegotiation(now, _path)) {
  1147. return true;
  1148. }
  1149. if (payloadLength() != sizeof(int16_t)) {
  1150. return true;
  1151. }
  1152. int16_t remoteUtility = 0;
  1153. memcpy(&remoteUtility, payload(), sizeof(int16_t));
  1154. if (peer->bond()) {
  1155. peer->bond()->processIncomingPathNegotiationRequest(now, _path, Utils::ntoh(remoteUtility));
  1156. }
  1157. return true;
  1158. }
  1159. void IncomingPacket::_sendErrorNeedCredentials(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer,const uint64_t nwid)
  1160. {
  1161. Packet outp(source(),RR->identity.address(),Packet::VERB_ERROR);
  1162. outp.append((uint8_t)verb());
  1163. outp.append(packetId());
  1164. outp.append((uint8_t)Packet::ERROR_NEED_MEMBERSHIP_CERTIFICATE);
  1165. outp.append(nwid);
  1166. outp.armor(peer->key(),true,peer->aesKeysIfSupported());
  1167. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  1168. }
  1169. } // namespace ZeroTier