IncomingPacket.cpp 55 KB

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