IncomingPacket.cpp 55 KB

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