IncomingPacket.cpp 54 KB

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