IncomingPacket.cpp 53 KB

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