IncomingPacket.cpp 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  1. /*
  2. * Copyright (c)2019 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: 2023-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 "../include/ZeroTierOne.h"
  14. #include "Constants.hpp"
  15. #include "RuntimeEnvironment.hpp"
  16. #include "IncomingPacket.hpp"
  17. #include "Topology.hpp"
  18. #include "Switch.hpp"
  19. #include "Peer.hpp"
  20. #include "NetworkController.hpp"
  21. #include "SelfAwareness.hpp"
  22. #include "Salsa20.hpp"
  23. #include "Node.hpp"
  24. #include "CertificateOfMembership.hpp"
  25. #include "Capability.hpp"
  26. #include "Tag.hpp"
  27. #include "Revocation.hpp"
  28. #include "Trace.hpp"
  29. #include <stdio.h>
  30. #include <string.h>
  31. #include <stdlib.h>
  32. #include <list>
  33. namespace ZeroTier {
  34. bool IncomingPacket::tryDecode(const RuntimeEnvironment *RR,void *tPtr)
  35. {
  36. const Address sourceAddress(source());
  37. try {
  38. // Check for trusted paths or unencrypted HELLOs (HELLO is the only packet sent in the clear)
  39. const unsigned int c = cipher();
  40. bool trusted = false;
  41. if (c == ZT_PROTO_CIPHER_SUITE__NONE) {
  42. // If this is marked as a packet via a trusted path, check source address and path ID.
  43. // Obviously if no trusted paths are configured this always returns false and such
  44. // packets are dropped on the floor.
  45. const uint64_t tpid = trustedPathId();
  46. if (RR->topology->shouldInboundPathBeTrusted(_path->address(),tpid)) {
  47. trusted = true;
  48. } else {
  49. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,packetId(),sourceAddress,hops(),"path not trusted");
  50. return true;
  51. }
  52. } else if ((c == ZT_PROTO_CIPHER_SUITE__POLY1305_NONE)&&(verb() == Packet::VERB_HELLO)) {
  53. // Only HELLO is allowed in the clear, but will still have a MAC
  54. return _doHELLO(RR,tPtr,false);
  55. }
  56. const SharedPtr<Peer> peer(RR->topology->get(sourceAddress));
  57. if (peer) {
  58. if (!trusted) {
  59. if (!dearmor(peer->key())) {
  60. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,packetId(),sourceAddress,hops(),"invalid MAC");
  61. _path->recordInvalidPacket();
  62. return true;
  63. }
  64. }
  65. if (!uncompress()) {
  66. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),sourceAddress,hops(),Packet::VERB_NOP,"LZ4 decompression failed");
  67. return true;
  68. }
  69. const Packet::Verb v = verb();
  70. bool r = true;
  71. switch(v) {
  72. //case Packet::VERB_NOP:
  73. default: // ignore unknown verbs, but if they pass auth check they are "received"
  74. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),v,0,Packet::VERB_NOP,0);
  75. break;
  76. case Packet::VERB_HELLO: r = _doHELLO(RR,tPtr,true); break;
  77. case Packet::VERB_ACK: r = _doACK(RR,tPtr,peer); break;
  78. case Packet::VERB_QOS_MEASUREMENT: r = _doQOS_MEASUREMENT(RR,tPtr,peer); break;
  79. case Packet::VERB_ERROR: r = _doERROR(RR,tPtr,peer); break;
  80. case Packet::VERB_OK: r = _doOK(RR,tPtr,peer); break;
  81. case Packet::VERB_WHOIS: r = _doWHOIS(RR,tPtr,peer); break;
  82. case Packet::VERB_RENDEZVOUS: r = _doRENDEZVOUS(RR,tPtr,peer); break;
  83. case Packet::VERB_FRAME: r = _doFRAME(RR,tPtr,peer); break;
  84. case Packet::VERB_EXT_FRAME: r = _doEXT_FRAME(RR,tPtr,peer); break;
  85. case Packet::VERB_ECHO: r = _doECHO(RR,tPtr,peer); break;
  86. case Packet::VERB_MULTICAST_LIKE: r = _doMULTICAST_LIKE(RR,tPtr,peer); break;
  87. case Packet::VERB_NETWORK_CREDENTIALS: r = _doNETWORK_CREDENTIALS(RR,tPtr,peer); break;
  88. case Packet::VERB_NETWORK_CONFIG_REQUEST: r = _doNETWORK_CONFIG_REQUEST(RR,tPtr,peer); break;
  89. case Packet::VERB_NETWORK_CONFIG: r = _doNETWORK_CONFIG(RR,tPtr,peer); break;
  90. case Packet::VERB_MULTICAST_GATHER: r = _doMULTICAST_GATHER(RR,tPtr,peer); break;
  91. case Packet::VERB_MULTICAST_FRAME: r = _doMULTICAST_FRAME(RR,tPtr,peer); break;
  92. case Packet::VERB_PUSH_DIRECT_PATHS: r = _doPUSH_DIRECT_PATHS(RR,tPtr,peer); break;
  93. case Packet::VERB_USER_MESSAGE: r = _doUSER_MESSAGE(RR,tPtr,peer); break;
  94. case Packet::VERB_REMOTE_TRACE: r = _doREMOTE_TRACE(RR,tPtr,peer); break;
  95. case Packet::VERB_SET_LOCATOR: break;
  96. case Packet::VERB_WILL_RELAY: break;
  97. case Packet::VERB_EPHEMERAL_KEY: break;
  98. }
  99. return r;
  100. } else {
  101. RR->sw->requestWhois(tPtr,RR->node->now(),sourceAddress);
  102. return false;
  103. }
  104. } catch (int ztExcCode) {
  105. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),sourceAddress,hops(),verb(),"unexpected exception in tryDecode()");
  106. return true;
  107. } catch ( ... ) {
  108. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),sourceAddress,hops(),verb(),"unexpected exception in tryDecode()");
  109. return true;
  110. }
  111. }
  112. bool IncomingPacket::_doERROR(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  113. {
  114. const Packet::Verb inReVerb = (Packet::Verb)(*this)[ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB];
  115. const uint64_t inRePacketId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID);
  116. const Packet::ErrorCode errorCode = (Packet::ErrorCode)(*this)[ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE];
  117. uint64_t networkId = 0;
  118. /* Security note: we do not gate doERROR() with expectingReplyTo() to
  119. * avoid having to log every outgoing packet ID. Instead we put the
  120. * logic to determine whether we should consider an ERROR in each
  121. * error handler. In most cases these are only trusted in specific
  122. * circumstances. */
  123. switch(errorCode) {
  124. case Packet::ERROR_OBJ_NOT_FOUND:
  125. // Object not found, currently only meaningful from network controllers.
  126. if (inReVerb == Packet::VERB_NETWORK_CONFIG_REQUEST) {
  127. networkId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD);
  128. const SharedPtr<Network> network(RR->node->network(networkId));
  129. if ((network)&&(network->controller() == peer->address()))
  130. network->setNotFound();
  131. }
  132. break;
  133. case Packet::ERROR_UNSUPPORTED_OPERATION:
  134. // This can be sent in response to any operation, though right now we only
  135. // consider it meaningful from network controllers. This would indicate
  136. // that the queried node does not support acting as a controller.
  137. if (inReVerb == Packet::VERB_NETWORK_CONFIG_REQUEST) {
  138. networkId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD);
  139. const SharedPtr<Network> network(RR->node->network(networkId));
  140. if ((network)&&(network->controller() == peer->address()))
  141. network->setNotFound();
  142. }
  143. break;
  144. case Packet::ERROR_NEED_MEMBERSHIP_CERTIFICATE: {
  145. // Peers can send this to ask for a cert for a network.
  146. networkId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD);
  147. const SharedPtr<Network> network(RR->node->network(networkId));
  148. const int64_t now = RR->node->now();
  149. if ((network)&&(network->config().com))
  150. network->pushCredentialsNow(tPtr,peer->address(),now);
  151. } break;
  152. case Packet::ERROR_NETWORK_ACCESS_DENIED_: {
  153. // Network controller: network access denied.
  154. networkId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD);
  155. const SharedPtr<Network> network(RR->node->network(networkId));
  156. if ((network)&&(network->controller() == peer->address()))
  157. network->setAccessDenied();
  158. } break;
  159. case Packet::ERROR_MULTICAST_STFU: {
  160. // Members of networks can use this error to indicate that they no longer
  161. // want to receive multicasts on a given channel.
  162. const MulticastGroup mg(MAC(field(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD + 8,6),6),at<uint32_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD + 14));
  163. RR->mc->remove(at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD),mg,peer->address());
  164. } break;
  165. default: break;
  166. }
  167. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_ERROR,inRePacketId,inReVerb,networkId);
  168. return true;
  169. }
  170. bool IncomingPacket::_doACK(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  171. {
  172. if (!peer->rateGateACK(RR->node->now()))
  173. return true;
  174. /* Dissect incoming ACK packet. From this we can estimate current throughput of the path, establish known
  175. * maximums and detect packet loss. */
  176. if (peer->localMultipathSupport()) {
  177. int32_t ackedBytes;
  178. if (payloadLength() != sizeof(ackedBytes)) {
  179. return true; // ignore
  180. }
  181. memcpy(&ackedBytes, payload(), sizeof(ackedBytes));
  182. _path->receivedAck(RR->node->now(), Utils::ntoh(ackedBytes));
  183. peer->inferRemoteMultipathEnabled();
  184. }
  185. return true;
  186. }
  187. bool IncomingPacket::_doQOS_MEASUREMENT(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  188. {
  189. if (!peer->rateGateQoS(RR->node->now()))
  190. return true;
  191. /* Dissect incoming QoS packet. From this we can compute latency values and their variance.
  192. * The latency variance is used as a measure of "jitter". */
  193. if (peer->localMultipathSupport()) {
  194. if (payloadLength() > ZT_PATH_MAX_QOS_PACKET_SZ || payloadLength() < ZT_PATH_MIN_QOS_PACKET_SZ) {
  195. return true; // ignore
  196. }
  197. const int64_t now = RR->node->now();
  198. uint64_t rx_id[ZT_PATH_QOS_TABLE_SIZE];
  199. uint16_t rx_ts[ZT_PATH_QOS_TABLE_SIZE];
  200. char *begin = (char *)payload();
  201. char *ptr = begin;
  202. int count = 0;
  203. int len = payloadLength();
  204. // Read packet IDs and latency compensation intervals for each packet tracked by this QoS packet
  205. while (ptr < (begin + len) && (count < ZT_PATH_QOS_TABLE_SIZE)) {
  206. memcpy((void*)&rx_id[count], ptr, sizeof(uint64_t));
  207. ptr+=sizeof(uint64_t);
  208. memcpy((void*)&rx_ts[count], ptr, sizeof(uint16_t));
  209. ptr+=sizeof(uint16_t);
  210. count++;
  211. }
  212. _path->receivedQoS(now, count, rx_id, rx_ts);
  213. peer->inferRemoteMultipathEnabled();
  214. }
  215. return true;
  216. }
  217. bool IncomingPacket::_doHELLO(const RuntimeEnvironment *RR,void *tPtr,const bool alreadyAuthenticated)
  218. {
  219. const int64_t now = RR->node->now();
  220. const uint64_t pid = packetId();
  221. const Address fromAddress(source());
  222. const unsigned int protoVersion = (*this)[ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION];
  223. const unsigned int vMajor = (*this)[ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION];
  224. const unsigned int vMinor = (*this)[ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION];
  225. const unsigned int vRevision = at<uint16_t>(ZT_PROTO_VERB_HELLO_IDX_REVISION);
  226. const int64_t timestamp = at<int64_t>(ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP);
  227. Identity id;
  228. unsigned int ptr = ZT_PROTO_VERB_HELLO_IDX_IDENTITY + id.deserialize(*this,ZT_PROTO_VERB_HELLO_IDX_IDENTITY);
  229. if (protoVersion < ZT_PROTO_VERSION_MIN) {
  230. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"protocol version too old");
  231. return true;
  232. }
  233. if (fromAddress != id.address()) {
  234. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"identity/address mismatch");
  235. return true;
  236. }
  237. SharedPtr<Peer> peer(RR->topology->get(id.address()));
  238. if (peer) {
  239. // We already have an identity with this address -- check for collisions
  240. if (!alreadyAuthenticated) {
  241. if (peer->identity() != id) {
  242. // Identity is different from the one we already have -- address collision
  243. // Check rate limits
  244. if (!RR->node->rateGateIdentityVerification(now,_path->address()))
  245. return true;
  246. uint8_t key[ZT_PEER_SECRET_KEY_LENGTH];
  247. if (RR->identity.agree(id,key)) {
  248. if (dearmor(key)) { // ensure packet is authentic, otherwise drop
  249. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"address collision");
  250. Packet outp(id.address(),RR->identity.address(),Packet::VERB_ERROR);
  251. outp.append((uint8_t)Packet::VERB_HELLO);
  252. outp.append((uint64_t)pid);
  253. outp.append((uint8_t)Packet::ERROR_IDENTITY_COLLISION);
  254. outp.armor(key,true);
  255. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  256. } else {
  257. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,pid,fromAddress,hops(),"invalid MAC");
  258. }
  259. } else {
  260. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,pid,fromAddress,hops(),"invalid identity");
  261. }
  262. return true;
  263. } else {
  264. // Identity is the same as the one we already have -- check packet integrity
  265. if (!dearmor(peer->key())) {
  266. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,pid,fromAddress,hops(),"invalid MAC");
  267. return true;
  268. }
  269. // Continue at // VALID
  270. }
  271. } // else if alreadyAuthenticated then continue at // VALID
  272. } else {
  273. // We don't already have an identity with this address -- validate and learn it
  274. // Sanity check: this basically can't happen
  275. if (alreadyAuthenticated) {
  276. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"illegal alreadyAuthenticated state");
  277. return true;
  278. }
  279. // Check rate limits
  280. if (!RR->node->rateGateIdentityVerification(now,_path->address())) {
  281. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"rate limit exceeded");
  282. return true;
  283. }
  284. // Check packet integrity and MAC (this is faster than locallyValidate() so do it first to filter out total crap)
  285. SharedPtr<Peer> newPeer(new Peer(RR,RR->identity,id));
  286. if (!dearmor(newPeer->key())) {
  287. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,pid,fromAddress,hops(),"invalid MAC");
  288. return true;
  289. }
  290. // Check that identity's address is valid as per the derivation function
  291. if (!id.locallyValidate()) {
  292. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"invalid identity");
  293. return true;
  294. }
  295. peer = RR->topology->add(newPeer);
  296. // Continue at // VALID
  297. }
  298. // VALID -- if we made it here, packet passed identity and authenticity checks!
  299. // Get address to which this packet was sent to learn our external surface address if packet was direct.
  300. if (hops() == 0) {
  301. InetAddress externalSurfaceAddress;
  302. if (ptr < size()) {
  303. ptr += externalSurfaceAddress.deserialize(*this,ptr);
  304. if ((externalSurfaceAddress)&&(hops() == 0))
  305. RR->sa->iam(tPtr,id.address(),_path->localSocket(),_path->address(),externalSurfaceAddress,RR->topology->isRoot(id),now);
  306. }
  307. }
  308. // Send OK(HELLO) with an echo of the packet's timestamp and some of the same
  309. // information about us: version, sent-to address, etc.
  310. Packet outp(id.address(),RR->identity.address(),Packet::VERB_OK);
  311. outp.append((unsigned char)Packet::VERB_HELLO);
  312. outp.append((uint64_t)pid);
  313. outp.append((uint64_t)timestamp);
  314. outp.append((unsigned char)ZT_PROTO_VERSION);
  315. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  316. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  317. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  318. _path->address().serialize(outp);
  319. outp.armor(peer->key(),true);
  320. _path->send(RR,tPtr,outp.data(),outp.size(),now);
  321. peer->setRemoteVersion(protoVersion,vMajor,vMinor,vRevision); // important for this to go first so received() knows the version
  322. peer->received(tPtr,_path,hops(),pid,payloadLength(),Packet::VERB_HELLO,0,Packet::VERB_NOP,0);
  323. return true;
  324. }
  325. bool IncomingPacket::_doOK(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  326. {
  327. const Packet::Verb inReVerb = (Packet::Verb)(*this)[ZT_PROTO_VERB_OK_IDX_IN_RE_VERB];
  328. const uint64_t inRePacketId = at<uint64_t>(ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID);
  329. uint64_t networkId = 0;
  330. if (!RR->node->expectingReplyTo(inRePacketId))
  331. return true;
  332. switch(inReVerb) {
  333. case Packet::VERB_HELLO: {
  334. const uint64_t latency = RR->node->now() - at<uint64_t>(ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP);
  335. const unsigned int vProto = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION];
  336. const unsigned int vMajor = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION];
  337. const unsigned int vMinor = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION];
  338. const unsigned int vRevision = at<uint16_t>(ZT_PROTO_VERB_HELLO__OK__IDX_REVISION);
  339. if (vProto < ZT_PROTO_VERSION_MIN)
  340. return true;
  341. if (hops() == 0) {
  342. _path->updateLatency((unsigned int)latency,RR->node->now());
  343. if ((ZT_PROTO_VERB_HELLO__OK__IDX_REVISION + 2) < size()) {
  344. InetAddress externalSurfaceAddress;
  345. externalSurfaceAddress.deserialize(*this,ZT_PROTO_VERB_HELLO__OK__IDX_REVISION + 2);
  346. if (externalSurfaceAddress)
  347. RR->sa->iam(tPtr,peer->address(),_path->localSocket(),_path->address(),externalSurfaceAddress,RR->topology->isRoot(peer->identity()),RR->node->now());
  348. }
  349. }
  350. peer->setRemoteVersion(vProto,vMajor,vMinor,vRevision);
  351. } break;
  352. case Packet::VERB_WHOIS:
  353. if (RR->topology->isRoot(peer->identity())) {
  354. unsigned int p = ZT_PROTO_VERB_WHOIS__OK__IDX_IDENTITY;
  355. while (p < size()) {
  356. try {
  357. Identity id;
  358. p += id.deserialize(*this,p);
  359. if (id)
  360. RR->sw->doAnythingWaitingForPeer(tPtr,RR->topology->add(SharedPtr<Peer>(new Peer(RR,RR->identity,id))));
  361. } catch ( ... ) {
  362. break;
  363. }
  364. }
  365. }
  366. break;
  367. case Packet::VERB_NETWORK_CONFIG_REQUEST: {
  368. networkId = at<uint64_t>(ZT_PROTO_VERB_OK_IDX_PAYLOAD);
  369. const SharedPtr<Network> network(RR->node->network(networkId));
  370. if (network)
  371. network->handleConfigChunk(tPtr,packetId(),source(),*this,ZT_PROTO_VERB_OK_IDX_PAYLOAD);
  372. } break;
  373. case Packet::VERB_MULTICAST_GATHER: {
  374. // TODO
  375. /*
  376. networkId = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID);
  377. const SharedPtr<Network> network(RR->node->network(networkId));
  378. if (network) {
  379. 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));
  380. const unsigned int count = at<uint16_t>(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_GATHER_RESULTS + 4);
  381. if (((ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_GATHER_RESULTS + 6) + (count * 5)) <= size())
  382. 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));
  383. }
  384. */
  385. } break;
  386. default: break;
  387. }
  388. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_OK,inRePacketId,inReVerb,networkId);
  389. return true;
  390. }
  391. bool IncomingPacket::_doWHOIS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  392. {
  393. if (!peer->rateGateInboundWhoisRequest(RR->node->now()))
  394. return true;
  395. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  396. outp.append((unsigned char)Packet::VERB_WHOIS);
  397. outp.append(packetId());
  398. unsigned int count = 0;
  399. unsigned int ptr = ZT_PACKET_IDX_PAYLOAD;
  400. while ((ptr + ZT_ADDRESS_LENGTH) <= size()) {
  401. const Address addr(field(ptr,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  402. ptr += ZT_ADDRESS_LENGTH;
  403. const Identity id(RR->topology->getIdentity(tPtr,addr));
  404. if (id) {
  405. id.serialize(outp,false);
  406. ++count;
  407. } else {
  408. // Request unknown WHOIS from upstream from us (if we have one)
  409. RR->sw->requestWhois(tPtr,RR->node->now(),addr);
  410. }
  411. }
  412. if (count > 0) {
  413. outp.armor(peer->key(),true);
  414. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  415. }
  416. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_WHOIS,0,Packet::VERB_NOP,0);
  417. return true;
  418. }
  419. bool IncomingPacket::_doRENDEZVOUS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  420. {
  421. if (RR->topology->isRoot(peer->identity())) {
  422. const Address with(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  423. const SharedPtr<Peer> rendezvousWith(RR->topology->get(with));
  424. if (rendezvousWith) {
  425. const unsigned int port = at<uint16_t>(ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT);
  426. const unsigned int addrlen = (*this)[ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN];
  427. if ((port > 0)&&((addrlen == 4)||(addrlen == 16))) {
  428. InetAddress atAddr(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS,addrlen),addrlen,port);
  429. if (RR->node->shouldUsePathForZeroTierTraffic(tPtr,with,_path->localSocket(),atAddr)) {
  430. const uint64_t junk = Utils::random();
  431. RR->node->putPacket(tPtr,_path->localSocket(),atAddr,&junk,4,2); // send low-TTL junk packet to 'open' local NAT(s) and stateful firewalls
  432. rendezvousWith->sendHELLO(tPtr,_path->localSocket(),atAddr,RR->node->now());
  433. }
  434. }
  435. }
  436. }
  437. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_RENDEZVOUS,0,Packet::VERB_NOP,0);
  438. return true;
  439. }
  440. bool IncomingPacket::_doFRAME(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  441. {
  442. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID);
  443. const SharedPtr<Network> network(RR->node->network(nwid));
  444. if (network) {
  445. if (network->gate(tPtr,peer)) {
  446. if (size() > ZT_PROTO_VERB_FRAME_IDX_PAYLOAD) {
  447. const unsigned int etherType = at<uint16_t>(ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE);
  448. const MAC sourceMac(peer->address(),nwid);
  449. const unsigned int frameLen = size() - ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  450. const uint8_t *const frameData = reinterpret_cast<const uint8_t *>(data()) + ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  451. if (network->filterIncomingPacket(tPtr,peer,RR->identity.address(),sourceMac,network->mac(),frameData,frameLen,etherType,0) > 0)
  452. RR->node->putFrame(tPtr,nwid,network->userPtr(),sourceMac,network->mac(),etherType,0,(const void *)frameData,frameLen);
  453. }
  454. } else {
  455. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  456. return false;
  457. }
  458. }
  459. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_FRAME,0,Packet::VERB_NOP,nwid);
  460. return true;
  461. }
  462. bool IncomingPacket::_doEXT_FRAME(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  463. {
  464. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID);
  465. const SharedPtr<Network> network(RR->node->network(nwid));
  466. if (network) {
  467. const unsigned int flags = (*this)[ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS];
  468. unsigned int comLen = 0;
  469. if ((flags & 0x01) != 0) { // inline COM with EXT_FRAME is deprecated but still used with old peers
  470. CertificateOfMembership com;
  471. comLen = com.deserialize(*this,ZT_PROTO_VERB_EXT_FRAME_IDX_COM);
  472. if (com)
  473. network->addCredential(tPtr,com);
  474. }
  475. if (!network->gate(tPtr,peer)) {
  476. RR->t->incomingNetworkAccessDenied(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,true);
  477. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  478. return false;
  479. }
  480. if (size() > ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD) {
  481. const unsigned int etherType = at<uint16_t>(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE);
  482. 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);
  483. 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);
  484. const unsigned int frameLen = size() - (comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD);
  485. const uint8_t *const frameData = (const uint8_t *)field(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD,frameLen);
  486. if ((!from)||(from == network->mac())) {
  487. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,nwid);
  488. return true;
  489. }
  490. switch (network->filterIncomingPacket(tPtr,peer,RR->identity.address(),from,to,frameData,frameLen,etherType,0)) {
  491. case 1:
  492. if (from != MAC(peer->address(),nwid)) {
  493. if (network->config().permitsBridging(peer->address())) {
  494. network->learnBridgeRoute(from,peer->address());
  495. } else {
  496. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,from,to,"bridging not allowed (remote)");
  497. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,nwid);
  498. return true;
  499. }
  500. } else if (to != network->mac()) {
  501. if (to.isMulticast()) {
  502. if (network->config().multicastLimit == 0) {
  503. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,from,to,"multicast disabled");
  504. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,nwid);
  505. return true;
  506. }
  507. } else if (!network->config().permitsBridging(RR->identity.address())) {
  508. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,from,to,"bridging not allowed (local)");
  509. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,nwid);
  510. return true;
  511. }
  512. }
  513. // fall through -- 2 means accept regardless of bridging checks or other restrictions
  514. case 2:
  515. RR->node->putFrame(tPtr,nwid,network->userPtr(),from,to,etherType,0,(const void *)frameData,frameLen);
  516. break;
  517. }
  518. }
  519. if ((flags & 0x10) != 0) { // ACK requested
  520. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  521. outp.append((uint8_t)Packet::VERB_EXT_FRAME);
  522. outp.append((uint64_t)packetId());
  523. outp.append((uint64_t)nwid);
  524. outp.armor(peer->key(),true);
  525. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  526. }
  527. }
  528. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,nwid);
  529. return true;
  530. }
  531. bool IncomingPacket::_doECHO(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  532. {
  533. if (!peer->rateGateEchoRequest(RR->node->now()))
  534. return true;
  535. const uint64_t pid = packetId();
  536. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  537. outp.append((unsigned char)Packet::VERB_ECHO);
  538. outp.append((uint64_t)pid);
  539. if (size() > ZT_PACKET_IDX_PAYLOAD)
  540. outp.append(reinterpret_cast<const unsigned char *>(data()) + ZT_PACKET_IDX_PAYLOAD,size() - ZT_PACKET_IDX_PAYLOAD);
  541. outp.armor(peer->key(),true);
  542. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  543. peer->received(tPtr,_path,hops(),pid,payloadLength(),Packet::VERB_ECHO,0,Packet::VERB_NOP,0);
  544. return true;
  545. }
  546. bool IncomingPacket::_doMULTICAST_LIKE(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  547. {
  548. const int64_t now = RR->node->now();
  549. bool authorized = false;
  550. uint64_t lastNwid = 0;
  551. // Packet contains a series of 18-byte network,MAC,ADI tuples
  552. for(unsigned int ptr=ZT_PACKET_IDX_PAYLOAD;(ptr+18)<=size();ptr+=18) {
  553. // TODO
  554. /*
  555. const uint64_t nwid = at<uint64_t>(ptr);
  556. if (nwid != lastNwid) {
  557. lastNwid = nwid;
  558. SharedPtr<Network> network(RR->node->network(nwid));
  559. if (network)
  560. authorized = network->gate(tPtr,peer);
  561. //if (!authorized)
  562. // authorized = ((RR->topology->amUpstream())||(RR->node->localControllerHasAuthorized(now,nwid,peer->address())));
  563. }
  564. if (authorized)
  565. RR->mc->add(tPtr,now,nwid,MulticastGroup(MAC(field(ptr + 8,6),6),at<uint32_t>(ptr + 14)),peer->address());
  566. */
  567. }
  568. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_MULTICAST_LIKE,0,Packet::VERB_NOP,0);
  569. return true;
  570. }
  571. bool IncomingPacket::_doNETWORK_CREDENTIALS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  572. {
  573. if (!peer->rateGateCredentialsReceived(RR->node->now()))
  574. return true;
  575. CertificateOfMembership com;
  576. Capability cap;
  577. Tag tag;
  578. Revocation revocation;
  579. CertificateOfOwnership coo;
  580. SharedPtr<Network> network;
  581. unsigned int p = ZT_PACKET_IDX_PAYLOAD;
  582. while ((p < size())&&((*this)[p] != 0)) {
  583. p += com.deserialize(*this,p);
  584. if (com) {
  585. network = RR->node->network(com.networkId());
  586. if (network) {
  587. if (network->addCredential(tPtr,com) == Membership::ADD_DEFERRED_FOR_WHOIS)
  588. return false;
  589. }
  590. }
  591. }
  592. ++p; // skip trailing 0 after COMs if present
  593. if (p < size()) { // older ZeroTier versions do not send capabilities, tags, or revocations
  594. const unsigned int numCapabilities = at<uint16_t>(p); p += 2;
  595. for(unsigned int i=0;i<numCapabilities;++i) {
  596. p += cap.deserialize(*this,p);
  597. if ((!network)||(network->id() != cap.networkId()))
  598. network = RR->node->network(cap.networkId());
  599. if (network) {
  600. if (network->addCredential(tPtr,cap) == Membership::ADD_DEFERRED_FOR_WHOIS)
  601. return false;
  602. }
  603. }
  604. if (p >= size()) return true;
  605. const unsigned int numTags = at<uint16_t>(p); p += 2;
  606. for(unsigned int i=0;i<numTags;++i) {
  607. p += tag.deserialize(*this,p);
  608. if ((!network)||(network->id() != tag.networkId()))
  609. network = RR->node->network(tag.networkId());
  610. if (network) {
  611. if (network->addCredential(tPtr,tag) == Membership::ADD_DEFERRED_FOR_WHOIS)
  612. return false;
  613. }
  614. }
  615. if (p >= size()) return true;
  616. const unsigned int numRevocations = at<uint16_t>(p); p += 2;
  617. for(unsigned int i=0;i<numRevocations;++i) {
  618. p += revocation.deserialize(*this,p);
  619. if ((!network)||(network->id() != revocation.networkId()))
  620. network = RR->node->network(revocation.networkId());
  621. if (network) {
  622. if (network->addCredential(tPtr,peer->address(),revocation) == Membership::ADD_DEFERRED_FOR_WHOIS)
  623. return false;
  624. }
  625. }
  626. if (p >= size()) return true;
  627. const unsigned int numCoos = at<uint16_t>(p); p += 2;
  628. for(unsigned int i=0;i<numCoos;++i) {
  629. p += coo.deserialize(*this,p);
  630. if ((!network)||(network->id() != coo.networkId()))
  631. network = RR->node->network(coo.networkId());
  632. if (network) {
  633. if (network->addCredential(tPtr,coo) == Membership::ADD_DEFERRED_FOR_WHOIS)
  634. return false;
  635. }
  636. }
  637. }
  638. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_NETWORK_CREDENTIALS,0,Packet::VERB_NOP,(network) ? network->id() : 0);
  639. return true;
  640. }
  641. bool IncomingPacket::_doNETWORK_CONFIG_REQUEST(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  642. {
  643. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID);
  644. const unsigned int hopCount = hops();
  645. const uint64_t requestPacketId = packetId();
  646. if (RR->localNetworkController) {
  647. 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;
  648. const char *metaDataBytes = (metaDataLength != 0) ? (const char *)field(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT,metaDataLength) : (const char *)0;
  649. const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> metaData(metaDataBytes,metaDataLength);
  650. RR->localNetworkController->request(nwid,(hopCount > 0) ? InetAddress() : _path->address(),requestPacketId,peer->identity(),metaData);
  651. } else {
  652. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_ERROR);
  653. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  654. outp.append(requestPacketId);
  655. outp.append((unsigned char)Packet::ERROR_UNSUPPORTED_OPERATION);
  656. outp.append(nwid);
  657. outp.armor(peer->key(),true);
  658. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  659. }
  660. peer->received(tPtr,_path,hopCount,requestPacketId,payloadLength(),Packet::VERB_NETWORK_CONFIG_REQUEST,0,Packet::VERB_NOP,nwid);
  661. return true;
  662. }
  663. bool IncomingPacket::_doNETWORK_CONFIG(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  664. {
  665. const SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PACKET_IDX_PAYLOAD)));
  666. if (network) {
  667. const uint64_t configUpdateId = network->handleConfigChunk(tPtr,packetId(),source(),*this,ZT_PACKET_IDX_PAYLOAD);
  668. if (configUpdateId) {
  669. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  670. outp.append((uint8_t)Packet::VERB_ECHO);
  671. outp.append((uint64_t)packetId());
  672. outp.append((uint64_t)network->id());
  673. outp.append((uint64_t)configUpdateId);
  674. outp.armor(peer->key(),true);
  675. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  676. }
  677. }
  678. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_NETWORK_CONFIG,0,Packet::VERB_NOP,(network) ? network->id() : 0);
  679. return true;
  680. }
  681. bool IncomingPacket::_doMULTICAST_GATHER(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  682. {
  683. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID);
  684. const unsigned int flags = (*this)[ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS];
  685. const MulticastGroup mg(MAC(field(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC,6),6),at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI));
  686. const unsigned int gatherLimit = at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_GATHER_LIMIT);
  687. const SharedPtr<Network> network(RR->node->network(nwid));
  688. if ((flags & 0x01) != 0) {
  689. try {
  690. CertificateOfMembership com;
  691. com.deserialize(*this,ZT_PROTO_VERB_MULTICAST_GATHER_IDX_COM);
  692. if ((com)&&(network))
  693. network->addCredential(tPtr,com);
  694. } catch ( ... ) {} // discard invalid COMs
  695. }
  696. if (network) {
  697. if (!network->gate(tPtr,peer)) {
  698. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  699. return false;
  700. }
  701. }
  702. const int64_t now = RR->node->now();
  703. if (gatherLimit) {
  704. // TODO
  705. /*
  706. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  707. outp.append((unsigned char)Packet::VERB_MULTICAST_GATHER);
  708. outp.append(packetId());
  709. outp.append(nwid);
  710. mg.mac().appendTo(outp);
  711. outp.append((uint32_t)mg.adi());
  712. const unsigned int gatheredLocally = RR->mc->gather(peer->address(),nwid,mg,outp,gatherLimit);
  713. if (gatheredLocally > 0) {
  714. outp.armor(peer->key(),true);
  715. _path->send(RR,tPtr,outp.data(),outp.size(),now);
  716. }
  717. */
  718. }
  719. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_MULTICAST_GATHER,0,Packet::VERB_NOP,nwid);
  720. return true;
  721. }
  722. bool IncomingPacket::_doMULTICAST_FRAME(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  723. {
  724. unsigned int offset = ZT_PACKET_IDX_PAYLOAD;
  725. const uint64_t nwid = at<uint64_t>(offset); offset += 8;
  726. const unsigned int flags = (*this)[offset]; ++offset;
  727. const SharedPtr<Network> network(RR->node->network(nwid));
  728. if (network) {
  729. if ((flags & 0x01) != 0) {
  730. // This is deprecated but may still be sent by old peers
  731. CertificateOfMembership com;
  732. offset += com.deserialize(*this,offset);
  733. if (com)
  734. network->addCredential(tPtr,com);
  735. }
  736. if (!network->gate(tPtr,peer)) {
  737. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  738. return false;
  739. }
  740. unsigned int gatherLimit = 0;
  741. if ((flags & 0x02) != 0) {
  742. gatherLimit = at<uint32_t>(offset); offset += 4;
  743. }
  744. MAC from;
  745. if ((flags & 0x04) != 0) {
  746. from.setTo(field(offset,6),6); offset += 6;
  747. } else {
  748. from.fromAddress(peer->address(),nwid);
  749. }
  750. const unsigned int recipientsOffset = offset;
  751. std::list<Address> recipients;
  752. if ((flags & 0x08) != 0) {
  753. const unsigned int rc = at<uint16_t>(offset); offset += 2;
  754. for(unsigned int i=0;i<rc;++i) {
  755. const Address a(field(offset,5),5);
  756. if ((a != peer->address())&&(a != RR->identity.address())) {
  757. recipients.push_back(a);
  758. }
  759. offset += 5;
  760. }
  761. }
  762. const unsigned int afterRecipientsOffset = offset;
  763. const MulticastGroup to(MAC(field(offset,6),6),at<uint32_t>(offset + 6)); offset += 10;
  764. const unsigned int etherType = at<uint16_t>(offset); offset += 2;
  765. const unsigned int frameLen = size() - offset;
  766. if (network->config().multicastLimit == 0) {
  767. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_MULTICAST_FRAME,from,to.mac(),"multicast disabled");
  768. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,nwid);
  769. return true;
  770. }
  771. if (!to.mac().isMulticast()) {
  772. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),source(),hops(),Packet::VERB_MULTICAST_FRAME,"destination not multicast");
  773. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,nwid);
  774. return true;
  775. }
  776. if ((!from)||(from.isMulticast())||(from == network->mac())) {
  777. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),source(),hops(),Packet::VERB_MULTICAST_FRAME,"invalid source MAC");
  778. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,nwid);
  779. return true;
  780. }
  781. if ((frameLen > 0)&&(frameLen <= ZT_MAX_MTU)) {
  782. const uint8_t *const frameData = ((const uint8_t *)unsafeData()) + offset;
  783. if (network->filterIncomingPacket(tPtr,peer,RR->identity.address(),from,to.mac(),frameData,frameLen,etherType,0) > 0) {
  784. RR->node->putFrame(tPtr,nwid,network->userPtr(),from,to.mac(),etherType,0,(const void *)frameData,frameLen);
  785. }
  786. }
  787. if (!recipients.empty()) {
  788. // TODO
  789. /*
  790. const std::vector<Address> anchors = network->config().anchors();
  791. const bool amAnchor = (std::find(anchors.begin(),anchors.end(),RR->identity.address()) != anchors.end());
  792. for(std::list<Address>::iterator ra(recipients.begin());ra!=recipients.end();) {
  793. SharedPtr<Peer> recipient(RR->topology->get(*ra));
  794. if ((recipient)&&((recipient->remoteVersionProtocol() < 10)||(amAnchor))) {
  795. Packet outp(*ra,RR->identity.address(),Packet::VERB_MULTICAST_FRAME);
  796. outp.append(field(ZT_PACKET_IDX_PAYLOAD,recipientsOffset - ZT_PACKET_IDX_PAYLOAD),recipientsOffset - ZT_PACKET_IDX_PAYLOAD);
  797. outp.append(field(afterRecipientsOffset,size() - afterRecipientsOffset),size() - afterRecipientsOffset);
  798. RR->sw->send(tPtr,outp,true);
  799. recipients.erase(ra++);
  800. } else ++ra;
  801. }
  802. if (!recipients.empty()) {
  803. Packet outp(recipients.front(),RR->identity.address(),Packet::VERB_MULTICAST_FRAME);
  804. recipients.pop_front();
  805. outp.append(field(ZT_PACKET_IDX_PAYLOAD,recipientsOffset - ZT_PACKET_IDX_PAYLOAD),recipientsOffset - ZT_PACKET_IDX_PAYLOAD);
  806. if (!recipients.empty()) {
  807. outp.append((uint16_t)recipients.size());
  808. for(std::list<Address>::iterator ra(recipients.begin());ra!=recipients.end();++ra)
  809. ra->appendTo(outp);
  810. }
  811. outp.append(field(afterRecipientsOffset,size() - afterRecipientsOffset),size() - afterRecipientsOffset);
  812. RR->sw->send(tPtr,outp,true);
  813. }
  814. */
  815. }
  816. if (gatherLimit) { // DEPRECATED but still supported
  817. /*
  818. Packet outp(source(),RR->identity.address(),Packet::VERB_OK);
  819. outp.append((unsigned char)Packet::VERB_MULTICAST_FRAME);
  820. outp.append(packetId());
  821. outp.append(nwid);
  822. to.mac().appendTo(outp);
  823. outp.append((uint32_t)to.adi());
  824. outp.append((unsigned char)0x02); // flag 0x02 = contains gather results
  825. if (RR->mc->gather(peer->address(),nwid,to,outp,gatherLimit)) {
  826. outp.armor(peer->key(),true);
  827. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  828. }
  829. */
  830. }
  831. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,nwid);
  832. return true;
  833. } else {
  834. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  835. return false;
  836. }
  837. }
  838. bool IncomingPacket::_doPUSH_DIRECT_PATHS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  839. {
  840. const int64_t now = RR->node->now();
  841. // First, subject this to a rate limit
  842. if (!peer->rateGatePushDirectPaths(now)) {
  843. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_PUSH_DIRECT_PATHS,0,Packet::VERB_NOP,0);
  844. return true;
  845. }
  846. // Second, limit addresses by scope and type
  847. uint8_t countPerScope[ZT_INETADDRESS_MAX_SCOPE+1][2]; // [][0] is v4, [][1] is v6
  848. memset(countPerScope,0,sizeof(countPerScope));
  849. unsigned int count = at<uint16_t>(ZT_PACKET_IDX_PAYLOAD);
  850. unsigned int ptr = ZT_PACKET_IDX_PAYLOAD + 2;
  851. while (count--) { // if ptr overflows Buffer will throw
  852. /* unsigned int flags = (*this)[ptr++]; */ ++ptr;
  853. unsigned int extLen = at<uint16_t>(ptr); ptr += 2;
  854. ptr += extLen; // unused right now
  855. unsigned int addrType = (*this)[ptr++];
  856. unsigned int addrLen = (*this)[ptr++];
  857. switch(addrType) {
  858. case 4: {
  859. const InetAddress a(field(ptr,4),4,at<uint16_t>(ptr + 4));
  860. if ((!peer->hasActivePathTo(now,a)) && // not already known
  861. (RR->node->shouldUsePathForZeroTierTraffic(tPtr,peer->address(),-1,a)) ) // should use path
  862. {
  863. if (++countPerScope[(int)a.ipScope()][0] <= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY)
  864. peer->sendHELLO(tPtr,-1,a,now);
  865. }
  866. } break;
  867. case 6: {
  868. const InetAddress a(field(ptr,16),16,at<uint16_t>(ptr + 16));
  869. if ((!peer->hasActivePathTo(now,a)) && // not already known
  870. (RR->node->shouldUsePathForZeroTierTraffic(tPtr,peer->address(),-1,a)) ) // should use path
  871. {
  872. if (++countPerScope[(int)a.ipScope()][1] <= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY)
  873. peer->sendHELLO(tPtr,-1,a,now);
  874. }
  875. } break;
  876. }
  877. ptr += addrLen;
  878. }
  879. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_PUSH_DIRECT_PATHS,0,Packet::VERB_NOP,0);
  880. return true;
  881. }
  882. bool IncomingPacket::_doUSER_MESSAGE(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  883. {
  884. if (likely(size() >= (ZT_PACKET_IDX_PAYLOAD + 8))) {
  885. ZT_UserMessage um;
  886. um.origin = peer->address().toInt();
  887. um.typeId = at<uint64_t>(ZT_PACKET_IDX_PAYLOAD);
  888. um.data = reinterpret_cast<const void *>(reinterpret_cast<const uint8_t *>(data()) + ZT_PACKET_IDX_PAYLOAD + 8);
  889. um.length = size() - (ZT_PACKET_IDX_PAYLOAD + 8);
  890. RR->node->postEvent(tPtr,ZT_EVENT_USER_MESSAGE,reinterpret_cast<const void *>(&um));
  891. }
  892. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_USER_MESSAGE,0,Packet::VERB_NOP,0);
  893. return true;
  894. }
  895. bool IncomingPacket::_doREMOTE_TRACE(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  896. {
  897. ZT_RemoteTrace rt;
  898. const char *ptr = reinterpret_cast<const char *>(data()) + ZT_PACKET_IDX_PAYLOAD;
  899. const char *const eof = reinterpret_cast<const char *>(data()) + size();
  900. rt.origin = peer->address().toInt();
  901. rt.data = const_cast<char *>(ptr); // start of first string
  902. while (ptr < eof) {
  903. if (!*ptr) { // end of string
  904. rt.len = (unsigned int)(ptr - rt.data);
  905. if ((rt.len > 0)&&(rt.len <= ZT_MAX_REMOTE_TRACE_SIZE)) {
  906. RR->node->postEvent(tPtr,ZT_EVENT_REMOTE_TRACE,&rt);
  907. }
  908. rt.data = const_cast<char *>(++ptr); // start of next string, if any
  909. } else {
  910. ++ptr;
  911. }
  912. }
  913. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_REMOTE_TRACE,0,Packet::VERB_NOP,0);
  914. return true;
  915. }
  916. void IncomingPacket::_sendErrorNeedCredentials(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer,const uint64_t nwid)
  917. {
  918. Packet outp(source(),RR->identity.address(),Packet::VERB_ERROR);
  919. outp.append((uint8_t)verb());
  920. outp.append(packetId());
  921. outp.append((uint8_t)Packet::ERROR_NEED_MEMBERSHIP_CERTIFICATE);
  922. outp.append(nwid);
  923. outp.armor(peer->key(),true);
  924. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  925. }
  926. } // namespace ZeroTier