1
0

IncomingPacket.cpp 53 KB

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