IncomingPacket.cpp 55 KB

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