root.cpp 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295
  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. /*
  14. * This is a high-throughput minimal root server. It implements only
  15. * those functions of a ZT node that a root must perform and does so
  16. * using highly efficient multithreaded I/O code. It's only been
  17. * thoroughly tested on Linux but should also run on BSDs.
  18. *
  19. * Root configuration file format (JSON):
  20. *
  21. * {
  22. * "name": Name of this root for documentation/UI purposes (string)
  23. * "port": UDP port (int)
  24. * "httpPort": Local HTTP port for basic stats (int)
  25. * "relayMaxHops": Max hops (up to 7)
  26. * "planetFile": Location of planet file for pre-2.x peers (string)
  27. * "statsRoot": If present, path to periodically save stats files (string)
  28. * "s_siblings": [
  29. * {
  30. * "name": Sibling name for UI/documentation purposes (string)
  31. * "id": Full public identity of subling (string)
  32. * "ip": IP address of sibling (string)
  33. * "port": port of subling (for ZeroTier UDP) (int)
  34. * }, ...
  35. * ]
  36. * }
  37. *
  38. * The only required field is port. If statsRoot is present then files
  39. * are periodically written there containing the root's current state.
  40. * It should be a memory filesystem like /dev/shm on Linux as these
  41. * files are large and rewritten frequently and do not need to be
  42. * persisted.
  43. *
  44. * s_siblings are other root servers that should receive packets to peers
  45. * that we can't find. This can occur due to e.g. network topology
  46. * hiccups, IP blockages, etc. s_siblings are used in the order in which
  47. * they appear with the first alive sibling being used.
  48. */
  49. #include <Constants.hpp>
  50. #include <stdio.h>
  51. #include <stdlib.h>
  52. #include <unistd.h>
  53. #include <string.h>
  54. #include <fcntl.h>
  55. #include <signal.h>
  56. #include <errno.h>
  57. #include <sys/stat.h>
  58. #include <sys/types.h>
  59. #include <sys/socket.h>
  60. #include <sys/select.h>
  61. #include <sys/time.h>
  62. #include <sys/un.h>
  63. #include <sys/ioctl.h>
  64. #include <arpa/inet.h>
  65. #include <netinet/in.h>
  66. #include <netinet/ip.h>
  67. #include <netinet/ip6.h>
  68. #include <netinet/tcp.h>
  69. #include <netinet/udp.h>
  70. #include <json.hpp>
  71. #include <httplib.h>
  72. #include <Packet.hpp>
  73. #include <Utils.hpp>
  74. #include <Address.hpp>
  75. #include <Identity.hpp>
  76. #include <InetAddress.hpp>
  77. #include <Mutex.hpp>
  78. #include <SharedPtr.hpp>
  79. #include <MulticastGroup.hpp>
  80. #include <CertificateOfMembership.hpp>
  81. #include <OSUtils.hpp>
  82. #include <Meter.hpp>
  83. #include <string>
  84. #include <thread>
  85. #include <map>
  86. #include <set>
  87. #include <vector>
  88. #include <iostream>
  89. #include <unordered_map>
  90. #include <unordered_set>
  91. #include <vector>
  92. #include <atomic>
  93. #include <mutex>
  94. #include <sstream>
  95. #include "geoip-html.h"
  96. using namespace ZeroTier;
  97. using json = nlohmann::json;
  98. #ifdef MSG_DONTWAIT
  99. #define SENDTO_FLAGS MSG_DONTWAIT
  100. #else
  101. #define SENDTO_FLAGS 0
  102. #endif
  103. //////////////////////////////////////////////////////////////////////////////
  104. //////////////////////////////////////////////////////////////////////////////
  105. /**
  106. * RootPeer is a normal peer known to this root
  107. *
  108. * This can also be a sibling root, which is itself a peer. Sibling roots
  109. * are sent HELLO while for other peers we only listen for HELLO.
  110. */
  111. struct RootPeer
  112. {
  113. ZT_ALWAYS_INLINE RootPeer() : lastSend(0),lastReceive(0),lastSync(0),lastEcho(0),lastHello(0),vProto(-1),vMajor(-1),vMinor(-1),vRev(-1) {}
  114. ZT_ALWAYS_INLINE ~RootPeer() { Utils::burn(key,sizeof(key)); }
  115. Identity id; // Identity
  116. uint8_t key[32]; // Shared secret key
  117. InetAddress ip4,ip6; // IPv4 and IPv6 addresses
  118. int64_t lastSend; // Time of last send (any packet)
  119. int64_t lastReceive; // Time of last receive (any packet)
  120. int64_t lastSync; // Time of last data synchronization with LF or other root state backend (currently unused)
  121. int64_t lastEcho; // Time of last received ECHO
  122. int64_t lastHello; // Time of last received HELLO
  123. int vProto; // Protocol version
  124. int vMajor,vMinor,vRev; // Peer version or -1,-1,-1 if unknown
  125. std::mutex lock;
  126. AtomicCounter __refCount;
  127. };
  128. // Hashers for std::unordered_map
  129. struct IdentityHasher { ZT_ALWAYS_INLINE std::size_t operator()(const Identity &id) const { return (std::size_t)id.hashCode(); } };
  130. struct AddressHasher { ZT_ALWAYS_INLINE std::size_t operator()(const Address &a) const { return (std::size_t)a.toInt(); } };
  131. struct InetAddressHasher { ZT_ALWAYS_INLINE std::size_t operator()(const InetAddress &ip) const { return (std::size_t)ip.hashCode(); } };
  132. struct MulticastGroupHasher { ZT_ALWAYS_INLINE std::size_t operator()(const MulticastGroup &mg) const { return (std::size_t)mg.hashCode(); } };
  133. // An ordered tuple key representing an introduction of one peer to another
  134. struct RendezvousKey
  135. {
  136. RendezvousKey(const Address &aa,const Address &bb)
  137. {
  138. if (aa > bb) {
  139. a = aa;
  140. b = bb;
  141. } else {
  142. a = bb;
  143. b = aa;
  144. }
  145. }
  146. Address a,b;
  147. ZT_ALWAYS_INLINE bool operator==(const RendezvousKey &k) const { return ((a == k.a)&&(b == k.b)); }
  148. ZT_ALWAYS_INLINE bool operator!=(const RendezvousKey &k) const { return ((a != k.a)||(b != k.b)); }
  149. struct Hasher { ZT_ALWAYS_INLINE std::size_t operator()(const RendezvousKey &k) const { return (std::size_t)(k.a.toInt() ^ k.b.toInt()); } };
  150. };
  151. struct RendezvousStats
  152. {
  153. RendezvousStats() : count(0),ts(0) {}
  154. int64_t count;
  155. int64_t ts;
  156. };
  157. struct ForwardingStats
  158. {
  159. ForwardingStats() : bytes(0),ts(0),bps() {}
  160. uint64_t bytes;
  161. int64_t ts;
  162. Meter bps;
  163. };
  164. static int64_t s_startTime; // Time service was started
  165. static std::vector<int> s_ports; // Ports to bind for UDP traffic
  166. static int s_relayMaxHops = 0; // Max relay hops
  167. static Identity s_self; // My identity (including secret)
  168. static std::atomic_bool s_run; // Remains true until shutdown is ordered
  169. static json s_config; // JSON config file contents
  170. static std::string s_statsRoot; // Root to write stats, peers, etc.
  171. static std::atomic_bool s_geoInit; // True if geoIP data is initialized
  172. static Meter s_inputRate;
  173. static Meter s_outputRate;
  174. static Meter s_forwardRate;
  175. static Meter s_discardedForwardRate;
  176. static std::string s_planet;
  177. static std::unordered_map< uint64_t,std::unordered_map< MulticastGroup,std::unordered_map< Address,int64_t,AddressHasher >,MulticastGroupHasher > > s_multicastSubscriptions;
  178. static std::unordered_map< Identity,SharedPtr<RootPeer>,IdentityHasher > s_peersByIdentity;
  179. static std::unordered_map< Address,std::set< SharedPtr<RootPeer> >,AddressHasher > s_peersByVirtAddr;
  180. static std::unordered_map< InetAddress,std::set< SharedPtr<RootPeer> >,InetAddressHasher > s_peersByPhysAddr;
  181. static std::unordered_map< RendezvousKey,RendezvousStats,RendezvousKey::Hasher > s_rendezvousTracking;
  182. static std::unordered_map< Address,ForwardingStats,AddressHasher > s_lastForwardedTo;
  183. static std::map< std::pair< uint32_t,uint32_t >,std::pair< float,float > > s_geoIp4;
  184. static std::map< std::pair< std::array< uint64_t,2 >,std::array< uint64_t,2 > >,std::pair< float,float > > s_geoIp6;
  185. static std::mutex s_planet_l;
  186. static std::mutex s_siblings_l;
  187. static std::mutex s_multicastSubscriptions_l;
  188. static std::mutex s_peersByIdentity_l;
  189. static std::mutex s_peersByVirtAddr_l;
  190. static std::mutex s_peersByPhysAddr_l;
  191. static std::mutex s_rendezvousTracking_l;
  192. static std::mutex s_lastForwardedTo_l;
  193. //////////////////////////////////////////////////////////////////////////////
  194. //////////////////////////////////////////////////////////////////////////////
  195. static uint32_t ip4ToH32(const InetAddress &ip)
  196. {
  197. return Utils::ntoh((uint32_t)(((const struct sockaddr_in *)&ip)->sin_addr.s_addr));
  198. }
  199. static std::array< uint64_t,2 > ip6ToH128(const InetAddress &ip)
  200. {
  201. std::array<uint64_t,2> i128;
  202. memcpy(i128.data(),ip.rawIpData(),16);
  203. i128[0] = Utils::ntoh(i128[0]);
  204. i128[1] = Utils::ntoh(i128[1]);
  205. return i128;
  206. }
  207. static void handlePacket(const int v4s,const int v6s,const InetAddress *const ip,Packet &pkt)
  208. {
  209. char ipstr[128],ipstr2[128],astr[32],astr2[32],tmpstr[256];
  210. const bool fragment = pkt[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] == ZT_PACKET_FRAGMENT_INDICATOR;
  211. const Address source(pkt.source());
  212. const Address dest(pkt.destination());
  213. const int64_t now = OSUtils::now();
  214. s_inputRate.log(now,pkt.size());
  215. if ((!fragment)&&(!pkt.fragmented())&&(dest == s_self.address())) {
  216. SharedPtr<RootPeer> peer;
  217. // If this is an un-encrypted HELLO, either learn a new peer or verify
  218. // that this is a peer we already know.
  219. if ((pkt.cipher() == ZT_PROTO_CIPHER_SUITE__POLY1305_NONE)&&(pkt.verb() == Packet::VERB_HELLO)) {
  220. std::lock_guard<std::mutex> pbi_l(s_peersByIdentity_l);
  221. std::lock_guard<std::mutex> pbv_l(s_peersByVirtAddr_l);
  222. Identity id;
  223. if (id.deserialize(pkt,ZT_PROTO_VERB_HELLO_IDX_IDENTITY)) {
  224. {
  225. auto pById = s_peersByIdentity.find(id);
  226. if (pById != s_peersByIdentity.end()) {
  227. peer = pById->second;
  228. //printf("%s has %s (known (1))" ZT_EOL_S,ip->toString(ipstr),source().toString(astr));
  229. }
  230. }
  231. if (peer) {
  232. if (!pkt.dearmor(peer->key)) {
  233. printf("%s HELLO rejected: packet authentication failed" ZT_EOL_S,ip->toString(ipstr));
  234. return;
  235. }
  236. } else {
  237. peer.set(new RootPeer);
  238. if (s_self.agree(id,peer->key)) {
  239. if (pkt.dearmor(peer->key)) {
  240. if (!pkt.uncompress()) {
  241. printf("%s HELLO rejected: decompression failed" ZT_EOL_S,ip->toString(ipstr));
  242. return;
  243. }
  244. peer->id = id;
  245. peer->lastReceive = now;
  246. s_peersByIdentity.emplace(id,peer);
  247. s_peersByVirtAddr[id.address()].emplace(peer);
  248. } else {
  249. printf("%s HELLO rejected: packet authentication failed" ZT_EOL_S,ip->toString(ipstr));
  250. return;
  251. }
  252. } else {
  253. printf("%s HELLO rejected: key agreement failed" ZT_EOL_S,ip->toString(ipstr));
  254. return;
  255. }
  256. }
  257. }
  258. }
  259. // If it wasn't a HELLO, check to see if any known identities for the sender's
  260. // short ZT address successfully decrypt the packet.
  261. if (!peer) {
  262. std::lock_guard<std::mutex> pbv_l(s_peersByVirtAddr_l);
  263. auto peers = s_peersByVirtAddr.find(source);
  264. if (peers != s_peersByVirtAddr.end()) {
  265. for(auto p=peers->second.begin();p!=peers->second.end();++p) {
  266. if (pkt.dearmor((*p)->key)) {
  267. if (!pkt.uncompress()) {
  268. printf("%s packet rejected: decompression failed" ZT_EOL_S,ip->toString(ipstr));
  269. return;
  270. }
  271. peer = (*p);
  272. //printf("%s has %s (known (2))" ZT_EOL_S,ip->toString(ipstr),source().toString(astr));
  273. break;
  274. }
  275. }
  276. }
  277. }
  278. // If we found the peer, update IP and/or time and handle certain key packet types that the
  279. // root must concern itself with.
  280. if (peer) {
  281. std::lock_guard<std::mutex> pl(peer->lock);
  282. InetAddress *const peerIp = ip->isV4() ? &(peer->ip4) : &(peer->ip6);
  283. if (*peerIp != ip) {
  284. std::lock_guard<std::mutex> pbp_l(s_peersByPhysAddr_l);
  285. if (*peerIp) {
  286. auto prev = s_peersByPhysAddr.find(*peerIp);
  287. if (prev != s_peersByPhysAddr.end()) {
  288. prev->second.erase(peer);
  289. if (prev->second.empty())
  290. s_peersByPhysAddr.erase(prev);
  291. }
  292. }
  293. *peerIp = ip;
  294. s_peersByPhysAddr[ip].emplace(peer);
  295. }
  296. const int64_t now = OSUtils::now();
  297. peer->lastReceive = now;
  298. switch(pkt.verb()) {
  299. case Packet::VERB_HELLO:
  300. try {
  301. if ((now - peer->lastHello) > 500) {
  302. peer->lastHello = now;
  303. peer->vProto = (int)pkt[ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION];
  304. peer->vMajor = (int)pkt[ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION];
  305. peer->vMinor = (int)pkt[ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION];
  306. peer->vRev = (int)pkt.template at<uint16_t>(ZT_PROTO_VERB_HELLO_IDX_REVISION);
  307. const uint64_t origId = pkt.packetId();
  308. const uint64_t ts = pkt.template at<uint64_t>(ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP);
  309. pkt.reset(source,s_self.address(),Packet::VERB_OK);
  310. pkt.append((uint8_t)Packet::VERB_HELLO);
  311. pkt.append(origId);
  312. pkt.append(ts);
  313. pkt.append((uint8_t)ZT_PROTO_VERSION);
  314. pkt.append((uint8_t)0);
  315. pkt.append((uint8_t)0);
  316. pkt.append((uint16_t)0);
  317. ip->serialize(pkt);
  318. if (peer->vProto < 11) { // send planet file for pre-2.x peers
  319. std::lock_guard<std::mutex> pl(s_planet_l);
  320. if (s_planet.length() > 0) {
  321. pkt.append((uint16_t)s_planet.size());
  322. pkt.append((const uint8_t *)s_planet.data(),s_planet.size());
  323. }
  324. }
  325. pkt.armor(peer->key,true);
  326. sendto(ip->isV4() ? v4s : v6s,pkt.data(),pkt.size(),SENDTO_FLAGS,(const struct sockaddr *)ip,(socklen_t)((ip->ss_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6)));
  327. s_outputRate.log(now,pkt.size());
  328. peer->lastSend = now;
  329. }
  330. } catch ( ... ) {
  331. printf("* unexpected exception handling HELLO from %s" ZT_EOL_S,ip->toString(ipstr));
  332. }
  333. break;
  334. case Packet::VERB_ECHO:
  335. try {
  336. if ((now - peer->lastEcho) > 500) {
  337. peer->lastEcho = now;
  338. Packet outp(source,s_self.address(),Packet::VERB_OK);
  339. outp.append((uint8_t)Packet::VERB_ECHO);
  340. outp.append(pkt.packetId());
  341. outp.append(((const uint8_t *)pkt.data()) + ZT_PACKET_IDX_PAYLOAD,pkt.size() - ZT_PACKET_IDX_PAYLOAD);
  342. outp.compress();
  343. outp.armor(peer->key,true);
  344. sendto(ip->isV4() ? v4s : v6s,outp.data(),outp.size(),SENDTO_FLAGS,(const struct sockaddr *)ip,(socklen_t)((ip->ss_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6)));
  345. s_outputRate.log(now,outp.size());
  346. peer->lastSend = now;
  347. }
  348. } catch ( ... ) {
  349. printf("* unexpected exception handling ECHO from %s" ZT_EOL_S,ip->toString(ipstr));
  350. }
  351. case Packet::VERB_WHOIS:
  352. try {
  353. std::vector< SharedPtr<RootPeer> > results;
  354. {
  355. std::lock_guard<std::mutex> l(s_peersByVirtAddr_l);
  356. for(unsigned int ptr=ZT_PACKET_IDX_PAYLOAD;(ptr+ZT_ADDRESS_LENGTH)<=pkt.size();ptr+=ZT_ADDRESS_LENGTH) {
  357. auto peers = s_peersByVirtAddr.find(Address(pkt.field(ptr,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH));
  358. if (peers != s_peersByVirtAddr.end()) {
  359. for(auto p=peers->second.begin();p!=peers->second.end();++p)
  360. results.push_back(*p);
  361. }
  362. }
  363. }
  364. if (!results.empty()) {
  365. const uint64_t origId = pkt.packetId();
  366. pkt.reset(source,s_self.address(),Packet::VERB_OK);
  367. pkt.append((uint8_t)Packet::VERB_WHOIS);
  368. pkt.append(origId);
  369. for(auto p=results.begin();p!=results.end();++p)
  370. (*p)->id.serialize(pkt,false);
  371. pkt.armor(peer->key,true);
  372. sendto(ip->isV4() ? v4s : v6s,pkt.data(),pkt.size(),SENDTO_FLAGS,(const struct sockaddr *)ip,(socklen_t)((ip->ss_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6)));
  373. s_outputRate.log(now,pkt.size());
  374. peer->lastSend = now;
  375. }
  376. } catch ( ... ) {
  377. printf("* unexpected exception handling ECHO from %s" ZT_EOL_S,ip->toString(ipstr));
  378. }
  379. case Packet::VERB_MULTICAST_LIKE:
  380. try {
  381. std::lock_guard<std::mutex> l(s_multicastSubscriptions_l);
  382. for(unsigned int ptr=ZT_PACKET_IDX_PAYLOAD;(ptr+18)<=pkt.size();ptr+=18) {
  383. const uint64_t nwid = pkt.template at<uint64_t>(ptr);
  384. const MulticastGroup mg(MAC(pkt.field(ptr + 8,6),6),pkt.template at<uint32_t>(ptr + 14));
  385. s_multicastSubscriptions[nwid][mg][source] = now;
  386. //printf("%s %s subscribes to %s/%.8lx on network %.16llx" ZT_EOL_S,ip->toString(ipstr),source.toString(astr),mg.mac().toString(tmpstr),(unsigned long)mg.adi(),(unsigned long long)nwid);
  387. }
  388. } catch ( ... ) {
  389. printf("* unexpected exception handling MULTICAST_LIKE from %s" ZT_EOL_S,ip->toString(ipstr));
  390. }
  391. break;
  392. case Packet::VERB_MULTICAST_GATHER:
  393. try {
  394. const uint64_t nwid = pkt.template at<uint64_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID);
  395. //const unsigned int flags = pkt[ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS];
  396. const MulticastGroup mg(MAC(pkt.field(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC,6),6),pkt.template at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI));
  397. unsigned int gatherLimit = pkt.template at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_GATHER_LIMIT);
  398. if (gatherLimit > 255)
  399. gatherLimit = 255;
  400. const uint64_t origId = pkt.packetId();
  401. pkt.reset(source,s_self.address(),Packet::VERB_OK);
  402. pkt.append((uint8_t)Packet::VERB_MULTICAST_GATHER);
  403. pkt.append(origId);
  404. pkt.append(nwid);
  405. mg.mac().appendTo(pkt);
  406. pkt.append((uint32_t)mg.adi());
  407. {
  408. std::lock_guard<std::mutex> l(s_multicastSubscriptions_l);
  409. auto forNet = s_multicastSubscriptions.find(nwid);
  410. if (forNet != s_multicastSubscriptions.end()) {
  411. auto forGroup = forNet->second.find(mg);
  412. if (forGroup != forNet->second.end()) {
  413. pkt.append((uint32_t)forGroup->second.size());
  414. const unsigned int countAt = pkt.size();
  415. pkt.addSize(2);
  416. unsigned int l = 0;
  417. for(auto g=forGroup->second.begin();((l<gatherLimit)&&(g!=forGroup->second.end()));++g) {
  418. if (g->first != source) {
  419. ++l;
  420. g->first.appendTo(pkt);
  421. }
  422. }
  423. if (l > 0) {
  424. pkt.setAt<uint16_t>(countAt,(uint16_t)l);
  425. pkt.armor(peer->key,true);
  426. sendto(ip->isV4() ? v4s : v6s,pkt.data(),pkt.size(),SENDTO_FLAGS,(const struct sockaddr *)ip,(socklen_t)(ip->isV4() ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6)));
  427. s_outputRate.log(now,pkt.size());
  428. peer->lastSend = now;
  429. //printf("%s %s gathered %u subscribers to %s/%.8lx on network %.16llx" ZT_EOL_S,ip->toString(ipstr),source.toString(astr),l,mg.mac().toString(tmpstr),(unsigned long)mg.adi(),(unsigned long long)nwid);
  430. }
  431. }
  432. }
  433. }
  434. } catch ( ... ) {
  435. printf("* unexpected exception handling MULTICAST_GATHER from %s" ZT_EOL_S,ip->toString(ipstr));
  436. }
  437. break;
  438. default:
  439. break;
  440. }
  441. return;
  442. }
  443. }
  444. // If we made it here, we are forwarding this packet to someone else and also possibly
  445. // sending a RENDEZVOUS message.
  446. int hops = 0;
  447. bool introduce = false;
  448. if (fragment) {
  449. if ((hops = (int)reinterpret_cast<Packet::Fragment *>(&pkt)->incrementHops()) > s_relayMaxHops) {
  450. //printf("%s refused to forward to %s: max hop count exceeded" ZT_EOL_S,ip->toString(ipstr),dest.toString(astr));
  451. s_discardedForwardRate.log(now,pkt.size());
  452. return;
  453. }
  454. } else {
  455. if ((hops = (int)pkt.incrementHops()) > s_relayMaxHops) {
  456. //printf("%s refused to forward to %s: max hop count exceeded" ZT_EOL_S,ip->toString(ipstr),dest.toString(astr));
  457. s_discardedForwardRate.log(now,pkt.size());
  458. return;
  459. }
  460. if (hops == 1) {
  461. RendezvousKey rk(source,dest);
  462. std::lock_guard<std::mutex> l(s_rendezvousTracking_l);
  463. RendezvousStats &lr = s_rendezvousTracking[rk];
  464. if ((now - lr.ts) >= 30000) {
  465. ++lr.count;
  466. lr.ts = now;
  467. introduce = true;
  468. }
  469. }
  470. }
  471. std::vector< std::pair< InetAddress *,SharedPtr<RootPeer> > > toAddrs;
  472. {
  473. std::lock_guard<std::mutex> pbv_l(s_peersByVirtAddr_l);
  474. auto peers = s_peersByVirtAddr.find(dest);
  475. if (peers != s_peersByVirtAddr.end()) {
  476. for(auto p=peers->second.begin();p!=peers->second.end();++p) {
  477. if ((*p)->ip4) {
  478. toAddrs.push_back(std::pair< InetAddress *,SharedPtr<RootPeer> >(&((*p)->ip4),*p));
  479. } else if ((*p)->ip6) {
  480. toAddrs.push_back(std::pair< InetAddress *,SharedPtr<RootPeer> >(&((*p)->ip6),*p));
  481. }
  482. }
  483. }
  484. }
  485. if (toAddrs.empty()) {
  486. s_discardedForwardRate.log(now,pkt.size());
  487. return;
  488. }
  489. {
  490. std::lock_guard<std::mutex> l(s_lastForwardedTo_l);
  491. ForwardingStats &fs = s_lastForwardedTo[dest];
  492. fs.bytes += (uint64_t)pkt.size();
  493. fs.ts = now;
  494. fs.bps.log(now,pkt.size());
  495. }
  496. if (introduce) {
  497. std::lock_guard<std::mutex> l(s_peersByVirtAddr_l);
  498. auto sources = s_peersByVirtAddr.find(source);
  499. if (sources != s_peersByVirtAddr.end()) {
  500. for(auto a=sources->second.begin();a!=sources->second.end();++a) {
  501. for(auto b=toAddrs.begin();b!=toAddrs.end();++b) {
  502. if (((*a)->ip6)&&(b->second->ip6)) {
  503. //printf("* introducing %s(%s) to %s(%s)" ZT_EOL_S,ip->toString(ipstr),source.toString(astr),b->second->ip6.toString(ipstr2),dest.toString(astr2));
  504. // Introduce source to destination (V6)
  505. Packet outp(source,s_self.address(),Packet::VERB_RENDEZVOUS);
  506. outp.append((uint8_t)0);
  507. dest.appendTo(outp);
  508. outp.append((uint16_t)b->second->ip6.port());
  509. outp.append((uint8_t)16);
  510. outp.append((const uint8_t *)b->second->ip6.rawIpData(),16);
  511. outp.armor((*a)->key,true);
  512. sendto(v6s,outp.data(),outp.size(),SENDTO_FLAGS,(const struct sockaddr *)&((*a)->ip6),(socklen_t)sizeof(struct sockaddr_in6));
  513. s_outputRate.log(now,outp.size());
  514. (*a)->lastSend = now;
  515. // Introduce destination to source (V6)
  516. outp.reset(dest,s_self.address(),Packet::VERB_RENDEZVOUS);
  517. outp.append((uint8_t)0);
  518. source.appendTo(outp);
  519. outp.append((uint16_t)ip->port());
  520. outp.append((uint8_t)16);
  521. outp.append((const uint8_t *)ip->rawIpData(),16);
  522. outp.armor(b->second->key,true);
  523. sendto(v6s,outp.data(),outp.size(),SENDTO_FLAGS,(const struct sockaddr *)&(b->second->ip6),(socklen_t)sizeof(struct sockaddr_in6));
  524. s_outputRate.log(now,outp.size());
  525. b->second->lastSend = now;
  526. }
  527. if (((*a)->ip4)&&(b->second->ip4)) {
  528. //printf("* introducing %s(%s) to %s(%s)" ZT_EOL_S,ip->toString(ipstr),source.toString(astr),b->second->ip4.toString(ipstr2),dest.toString(astr2));
  529. // Introduce source to destination (V4)
  530. Packet outp(source,s_self.address(),Packet::VERB_RENDEZVOUS);
  531. outp.append((uint8_t)0);
  532. dest.appendTo(outp);
  533. outp.append((uint16_t)b->second->ip4.port());
  534. outp.append((uint8_t)4);
  535. outp.append((const uint8_t *)b->second->ip4.rawIpData(),4);
  536. outp.armor((*a)->key,true);
  537. sendto(v4s,outp.data(),outp.size(),SENDTO_FLAGS,(const struct sockaddr *)&((*a)->ip4),(socklen_t)sizeof(struct sockaddr_in));
  538. s_outputRate.log(now,outp.size());
  539. (*a)->lastSend = now;
  540. // Introduce destination to source (V4)
  541. outp.reset(dest,s_self.address(),Packet::VERB_RENDEZVOUS);
  542. outp.append((uint8_t)0);
  543. source.appendTo(outp);
  544. outp.append((uint16_t)ip->port());
  545. outp.append((uint8_t)4);
  546. outp.append((const uint8_t *)ip->rawIpData(),4);
  547. outp.armor(b->second->key,true);
  548. sendto(v4s,outp.data(),outp.size(),SENDTO_FLAGS,(const struct sockaddr *)&(b->second->ip4),(socklen_t)sizeof(struct sockaddr_in));
  549. s_outputRate.log(now,outp.size());
  550. b->second->lastSend = now;
  551. }
  552. }
  553. }
  554. }
  555. }
  556. for(auto i=toAddrs.begin();i!=toAddrs.end();++i) {
  557. //printf("%s -> %s for %s -> %s (%u bytes)" ZT_EOL_S,ip->toString(ipstr),i->first->toString(ipstr2),source.toString(astr),dest.toString(astr2),pkt.size());
  558. if (sendto(i->first->isV4() ? v4s : v6s,pkt.data(),pkt.size(),SENDTO_FLAGS,(const struct sockaddr *)i->first,(socklen_t)(i->first->isV4() ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6))) > 0) {
  559. s_outputRate.log(now,pkt.size());
  560. s_forwardRate.log(now,pkt.size());
  561. i->second->lastSend = now;
  562. }
  563. }
  564. }
  565. //////////////////////////////////////////////////////////////////////////////
  566. //////////////////////////////////////////////////////////////////////////////
  567. static int bindSocket(struct sockaddr *const bindAddr)
  568. {
  569. const int s = socket(bindAddr->sa_family,SOCK_DGRAM,0);
  570. if (s < 0) {
  571. close(s);
  572. return -1;
  573. }
  574. int f = 4194304;
  575. while (f > 131072) {
  576. if (setsockopt(s,SOL_SOCKET,SO_RCVBUF,(const char *)&f,sizeof(f)) == 0)
  577. break;
  578. f -= 131072;
  579. }
  580. f = 4194304;
  581. while (f > 131072) {
  582. if (setsockopt(s,SOL_SOCKET,SO_SNDBUF,(const char *)&f,sizeof(f)) == 0)
  583. break;
  584. f -= 131072;
  585. }
  586. if (bindAddr->sa_family == AF_INET6) {
  587. f = 1; setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f));
  588. #ifdef IPV6_MTU_DISCOVER
  589. f = 0; setsockopt(s,IPPROTO_IPV6,IPV6_MTU_DISCOVER,&f,sizeof(f));
  590. #endif
  591. #ifdef IPV6_DONTFRAG
  592. f = 0; setsockopt(s,IPPROTO_IPV6,IPV6_DONTFRAG,&f,sizeof(f));
  593. #endif
  594. }
  595. #ifdef IP_DONTFRAG
  596. f = 0; setsockopt(s,IPPROTO_IP,IP_DONTFRAG,&f,sizeof(f));
  597. #endif
  598. #ifdef IP_MTU_DISCOVER
  599. f = IP_PMTUDISC_DONT; setsockopt(s,IPPROTO_IP,IP_MTU_DISCOVER,&f,sizeof(f));
  600. #endif
  601. #ifdef SO_NO_CHECK
  602. if (bindAddr->sa_family == AF_INET) {
  603. f = 1; setsockopt(s,SOL_SOCKET,SO_NO_CHECK,(void *)&f,sizeof(f));
  604. }
  605. #endif
  606. #if defined(SO_REUSEPORT)
  607. f = 1; setsockopt(s,SOL_SOCKET,SO_REUSEPORT,(void *)&f,sizeof(f));
  608. #endif
  609. #ifndef __LINUX__ // linux wants just SO_REUSEPORT
  610. f = 1; setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  611. #endif
  612. if (bind(s,bindAddr,(bindAddr->sa_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6))) {
  613. close(s);
  614. //printf("%s\n",strerror(errno));
  615. return -1;
  616. }
  617. return s;
  618. }
  619. static void shutdownSigHandler(int sig) { s_run = false; }
  620. int main(int argc,char **argv)
  621. {
  622. std::vector<std::thread> threads;
  623. std::vector<int> sockets;
  624. int v4Sock = -1,v6Sock = -1;
  625. signal(SIGTERM,shutdownSigHandler);
  626. signal(SIGINT,shutdownSigHandler);
  627. signal(SIGQUIT,shutdownSigHandler);
  628. signal(SIGPIPE,SIG_IGN);
  629. signal(SIGUSR1,SIG_IGN);
  630. signal(SIGUSR2,SIG_IGN);
  631. signal(SIGCHLD,SIG_IGN);
  632. s_startTime = OSUtils::now();
  633. s_geoInit = false;
  634. if (argc < 3) {
  635. printf("Usage: zerotier-root <identity.secret> <config path>" ZT_EOL_S);
  636. return 1;
  637. }
  638. {
  639. std::string myIdStr;
  640. if (!OSUtils::readFile(argv[1],myIdStr)) {
  641. printf("FATAL: cannot read identity.secret at %s" ZT_EOL_S,argv[1]);
  642. return 1;
  643. }
  644. if (!s_self.fromString(myIdStr.c_str())) {
  645. printf("FATAL: cannot read identity.secret at %s (invalid identity)" ZT_EOL_S,argv[1]);
  646. return 1;
  647. }
  648. if (!s_self.hasPrivate()) {
  649. printf("FATAL: cannot read identity.secret at %s (missing secret key)" ZT_EOL_S,argv[1]);
  650. return 1;
  651. }
  652. }
  653. {
  654. std::string configStr;
  655. if (!OSUtils::readFile(argv[2],configStr)) {
  656. printf("FATAL: cannot read config file at %s" ZT_EOL_S,argv[2]);
  657. return 1;
  658. }
  659. try {
  660. s_config = json::parse(configStr);
  661. } catch (std::exception &exc) {
  662. printf("FATAL: config file at %s invalid: %s" ZT_EOL_S,argv[2],exc.what());
  663. return 1;
  664. } catch ( ... ) {
  665. printf("FATAL: config file at %s invalid: unknown exception" ZT_EOL_S,argv[2]);
  666. return 1;
  667. }
  668. if (!s_config.is_object()) {
  669. printf("FATAL: config file at %s invalid: does not contain a JSON object" ZT_EOL_S,argv[2]);
  670. return 1;
  671. }
  672. }
  673. try {
  674. auto jport = s_config["port"];
  675. if (jport.is_array()) {
  676. for(long i=0;i<(long)jport.size();++i) {
  677. int port = jport[i];
  678. if ((port <= 0)||(port > 65535)) {
  679. printf("FATAL: invalid port in config file %d" ZT_EOL_S,port);
  680. return 1;
  681. }
  682. s_ports.push_back(port);
  683. }
  684. } else {
  685. int port = jport;
  686. if ((port <= 0)||(port > 65535)) {
  687. printf("FATAL: invalid port in config file %d" ZT_EOL_S,port);
  688. return 1;
  689. }
  690. s_ports.push_back(port);
  691. }
  692. } catch ( ... ) {}
  693. if (s_ports.empty())
  694. s_ports.push_back(ZT_DEFAULT_PORT);
  695. std::sort(s_ports.begin(),s_ports.end());
  696. int httpPort = ZT_DEFAULT_PORT;
  697. try {
  698. httpPort = s_config["httpPort"];
  699. if ((httpPort <= 0)||(httpPort > 65535)) {
  700. printf("FATAL: invalid HTTP port in config file %d" ZT_EOL_S,httpPort);
  701. return 1;
  702. }
  703. } catch ( ... ) {
  704. httpPort = ZT_DEFAULT_PORT;
  705. }
  706. std::string planetFilePath;
  707. try {
  708. planetFilePath = s_config["planetFile"];
  709. } catch ( ... ) {
  710. planetFilePath = "";
  711. }
  712. try {
  713. s_statsRoot = s_config["statsRoot"];
  714. while ((s_statsRoot.length() > 0)&&(s_statsRoot[s_statsRoot.length()-1] == ZT_PATH_SEPARATOR))
  715. s_statsRoot = s_statsRoot.substr(0,s_statsRoot.length()-1);
  716. if (s_statsRoot.length() > 0)
  717. OSUtils::mkdir(s_statsRoot);
  718. } catch ( ... ) {
  719. s_statsRoot = "";
  720. }
  721. s_relayMaxHops = ZT_RELAY_MAX_HOPS;
  722. try {
  723. s_relayMaxHops = s_config["relayMaxHops"];
  724. if (s_relayMaxHops > ZT_PROTO_MAX_HOPS)
  725. s_relayMaxHops = ZT_PROTO_MAX_HOPS;
  726. else if (s_relayMaxHops < 0)
  727. s_relayMaxHops = 0;
  728. } catch ( ... ) {
  729. s_relayMaxHops = ZT_RELAY_MAX_HOPS;
  730. }
  731. try {
  732. std::string geoIpPath = s_config["geoIp"];
  733. if (geoIpPath.length() > 0) {
  734. FILE *gf = fopen(geoIpPath.c_str(),"rb");
  735. if (gf) {
  736. threads.emplace_back(std::thread([gf]() {
  737. try {
  738. char line[1024];
  739. line[1023] = 0;
  740. while (fgets(line,sizeof(line)-1,gf)) {
  741. InetAddress start,end;
  742. float lat = 0.0F,lon = 0.0F;
  743. int field = 0;
  744. for(char *saveptr=nullptr,*f=Utils::stok(line,",\r\n",&saveptr);(f);f=Utils::stok(nullptr,",\r\n",&saveptr)) {
  745. switch(field++) {
  746. case 0:
  747. start.fromString(f);
  748. break;
  749. case 1:
  750. end.fromString(f);
  751. break;
  752. case 2:
  753. lat = strtof(f,nullptr);
  754. break;
  755. case 3:
  756. lon = strtof(f,nullptr);
  757. break;
  758. }
  759. }
  760. if ((start)&&(end)&&(start.ss_family == end.ss_family)&&(lat >= -90.0F)&&(lat <= 90.0F)&&(lon >= -180.0F)&&(lon <= 180.0F)) {
  761. if (start.ss_family == AF_INET) {
  762. s_geoIp4[std::pair< uint32_t,uint32_t >(ip4ToH32(start),ip4ToH32(end))] = std::pair< float,float >(lat,lon);
  763. } else if (start.ss_family == AF_INET6) {
  764. s_geoIp6[std::pair< std::array< uint64_t,2 >,std::array< uint64_t,2 > >(ip6ToH128(start),ip6ToH128(end))] = std::pair< float,float >(lat,lon);
  765. }
  766. }
  767. }
  768. s_geoInit = true;
  769. } catch ( ... ) {}
  770. fclose(gf);
  771. }));
  772. }
  773. }
  774. } catch ( ... ) {}
  775. unsigned int ncores = std::thread::hardware_concurrency();
  776. if (ncores == 0) ncores = 1;
  777. s_run = true;
  778. for(auto port=s_ports.begin();port!=s_ports.end();++port) {
  779. for(unsigned int tn=0;tn<ncores;++tn) {
  780. struct sockaddr_in6 in6;
  781. memset(&in6,0,sizeof(in6));
  782. in6.sin6_family = AF_INET6;
  783. in6.sin6_port = htons((uint16_t)*port);
  784. const int s6 = bindSocket((struct sockaddr *)&in6);
  785. if (s6 < 0) {
  786. std::cout << "ERROR: unable to bind to port " << *port << ZT_EOL_S;
  787. exit(1);
  788. }
  789. struct sockaddr_in in4;
  790. memset(&in4,0,sizeof(in4));
  791. in4.sin_family = AF_INET;
  792. in4.sin_port = htons((uint16_t)*port);
  793. const int s4 = bindSocket((struct sockaddr *)&in4);
  794. if (s4 < 0) {
  795. std::cout << "ERROR: unable to bind to port " << *port << ZT_EOL_S;
  796. exit(1);
  797. }
  798. sockets.push_back(s6);
  799. sockets.push_back(s4);
  800. if (v4Sock < 0) v4Sock = s4;
  801. if (v6Sock < 0) v6Sock = s6;
  802. threads.push_back(std::thread([s6,s4]() {
  803. struct sockaddr_in6 in6;
  804. Packet pkt;
  805. memset(&in6,0,sizeof(in6));
  806. for(;;) {
  807. socklen_t sl = sizeof(in6);
  808. const int pl = (int)recvfrom(s6,pkt.unsafeData(),pkt.capacity(),0,(struct sockaddr *)&in6,&sl);
  809. if (pl > 0) {
  810. if (pl >= ZT_PROTO_MIN_FRAGMENT_LENGTH) {
  811. try {
  812. pkt.setSize((unsigned int)pl);
  813. handlePacket(s4,s6,reinterpret_cast<const InetAddress *>(&in6),pkt);
  814. } catch ( ... ) {
  815. char ipstr[128];
  816. printf("* unexpected exception handling packet from %s" ZT_EOL_S,reinterpret_cast<const InetAddress *>(&in6)->toString(ipstr));
  817. }
  818. }
  819. } else {
  820. break;
  821. }
  822. }
  823. }));
  824. threads.push_back(std::thread([s6,s4]() {
  825. struct sockaddr_in in4;
  826. Packet pkt;
  827. memset(&in4,0,sizeof(in4));
  828. for(;;) {
  829. socklen_t sl = sizeof(in4);
  830. const int pl = (int)recvfrom(s4,pkt.unsafeData(),pkt.capacity(),0,(struct sockaddr *)&in4,&sl);
  831. if (pl > 0) {
  832. if (pl >= ZT_PROTO_MIN_FRAGMENT_LENGTH) {
  833. try {
  834. pkt.setSize((unsigned int)pl);
  835. handlePacket(s4,s6,reinterpret_cast<const InetAddress *>(&in4),pkt);
  836. } catch ( ... ) {
  837. char ipstr[128];
  838. printf("* unexpected exception handling packet from %s" ZT_EOL_S,reinterpret_cast<const InetAddress *>(&in4)->toString(ipstr));
  839. }
  840. }
  841. } else {
  842. break;
  843. }
  844. }
  845. }));
  846. }
  847. }
  848. // Minimal local API for use with monitoring clients, etc.
  849. httplib::Server apiServ;
  850. threads.push_back(std::thread([&apiServ,httpPort]() {
  851. apiServ.Get("/",[](const httplib::Request &req,httplib::Response &res) {
  852. std::ostringstream o;
  853. std::lock_guard<std::mutex> l0(s_peersByIdentity_l);
  854. std::lock_guard<std::mutex> l1(s_peersByPhysAddr_l);
  855. o << "ZeroTier Root Server " << ZEROTIER_ONE_VERSION_MAJOR << '.' << ZEROTIER_ONE_VERSION_MINOR << '.' << ZEROTIER_ONE_VERSION_REVISION << ZT_EOL_S;
  856. o << "(c)2019 ZeroTier, Inc." ZT_EOL_S "Licensed under the ZeroTier BSL 1.1" ZT_EOL_S ZT_EOL_S;
  857. o << "Peers Online: " << s_peersByIdentity.size() << ZT_EOL_S;
  858. o << "Physical Addresses: " << s_peersByPhysAddr.size() << ZT_EOL_S;
  859. res.set_content(o.str(),"text/plain");
  860. });
  861. apiServ.Get("/peer",[](const httplib::Request &req,httplib::Response &res) {
  862. char tmp[256];
  863. std::ostringstream o;
  864. o << '[';
  865. {
  866. bool first = true;
  867. std::lock_guard<std::mutex> l(s_peersByIdentity_l);
  868. for(auto p=s_peersByIdentity.begin();p!=s_peersByIdentity.end();++p) {
  869. if (first)
  870. first = false;
  871. else o << ',';
  872. o <<
  873. "{\"address\":\"" << p->first.address().toString(tmp) << "\""
  874. ",\"latency\":-1"
  875. ",\"paths\":[";
  876. if (p->second->ip4) {
  877. o <<
  878. "{\"active\":true"
  879. ",\"address\":\"" << p->second->ip4.toIpString(tmp) << "\\/" << p->second->ip4.port() << "\""
  880. ",\"expired\":false"
  881. ",\"lastReceive\":" << p->second->lastReceive <<
  882. ",\"lastSend\":" << p->second->lastSend <<
  883. ",\"preferred\":true"
  884. ",\"trustedPathId\":0}";
  885. }
  886. if (p->second->ip6) {
  887. if (p->second->ip4)
  888. o << ',';
  889. o <<
  890. "{\"active\":true"
  891. ",\"address\":\"" << p->second->ip6.toIpString(tmp) << "\\/" << p->second->ip6.port() << "\""
  892. ",\"expired\":false"
  893. ",\"lastReceive\":" << p->second->lastReceive <<
  894. ",\"lastSend\":" << p->second->lastSend <<
  895. ",\"preferred\":" << ((p->second->ip4) ? "false" : "true") <<
  896. ",\"trustedPathId\":0}";
  897. }
  898. o << "]"
  899. ",\"role\":\"LEAF\""
  900. ",\"version\":\"" << p->second->vMajor << '.' << p->second->vMinor << '.' << p->second->vRev << "\""
  901. ",\"versionMajor\":" << p->second->vMajor <<
  902. ",\"versionMinor\":" << p->second->vMinor <<
  903. ",\"versionRev\":" << p->second->vRev << "}";
  904. }
  905. }
  906. o << ']';
  907. res.set_content(o.str(),"application/json");
  908. });
  909. apiServ.Get("/map",[](const httplib::Request &req,httplib::Response &res) {
  910. char tmp[128];
  911. if (!s_geoInit) {
  912. res.set_content("Not enabled or GeoIP CSV file not finished reading.","text/plain");
  913. return;
  914. }
  915. std::ostringstream o;
  916. o << ZT_GEOIP_HTML_HEAD;
  917. {
  918. bool firstCoord = true;
  919. std::pair< uint32_t,uint32_t > k4(0,0xffffffff);
  920. std::pair< std::array< uint64_t,2 >,std::array< uint64_t,2 > > k6;
  921. k6.second[0] = 0xffffffffffffffffULL; k6.second[1] = 0xffffffffffffffffULL;
  922. std::lock_guard<std::mutex> l(s_peersByPhysAddr_l);
  923. for(auto p=s_peersByPhysAddr.begin();p!=s_peersByPhysAddr.end();++p) {
  924. if (!p->second.empty()) {
  925. if (p->first.isV4()) {
  926. k4.first = ip4ToH32(p->first);
  927. auto geo = std::map< std::pair< uint32_t,uint32_t >,std::pair< float,float > >::reverse_iterator(s_geoIp4.upper_bound(k4));
  928. while (geo != s_geoIp4.rend()) {
  929. if ((geo->first.first <= k4.first)&&(geo->first.second >= k4.first)) {
  930. if (!firstCoord)
  931. o << ',';
  932. firstCoord = false;
  933. o << "{lat:" << geo->second.first << ",lng:" << geo->second.second << ",_l:\"";
  934. bool firstAddr = true;
  935. for(auto a=p->second.begin();a!=p->second.end();++a) {
  936. if (!firstAddr)
  937. o << ',';
  938. o << (*a)->id.address().toString(tmp);
  939. firstAddr = false;
  940. }
  941. o << "\"}";
  942. break;
  943. } else if ((geo->first.first < k4.first)&&(geo->first.second < k4.first)) {
  944. break;
  945. }
  946. ++geo;
  947. }
  948. } else if (p->first.isV6()) {
  949. k6.first = ip6ToH128(p->first);
  950. auto geo = std::map< std::pair< std::array< uint64_t,2 >,std::array< uint64_t,2 > >,std::pair< float,float > >::reverse_iterator(s_geoIp6.upper_bound(k6));
  951. while (geo != s_geoIp6.rend()) {
  952. if ((geo->first.first <= k6.first)&&(geo->first.second >= k6.first)) {
  953. if (!firstCoord)
  954. o << ',';
  955. firstCoord = false;
  956. o << "{lat:" << geo->second.first << ",lng:" << geo->second.second << ",_l:\"";
  957. bool firstAddr = true;
  958. for(auto a=p->second.begin();a!=p->second.end();++a) {
  959. if (!firstAddr)
  960. o << ',';
  961. o << (*a)->id.address().toString(tmp);
  962. firstAddr = false;
  963. }
  964. o << "\"}";
  965. break;
  966. } else if ((geo->first.first < k6.first)&&(geo->first.second < k6.first)) {
  967. break;
  968. }
  969. ++geo;
  970. }
  971. }
  972. }
  973. }
  974. }
  975. o << ZT_GEOIP_HTML_TAIL;
  976. res.set_content(o.str(),"text/html");
  977. });
  978. apiServ.listen("127.0.0.1",httpPort,0);
  979. }));
  980. // In the main thread periodically clean stuff up
  981. int64_t lastCleaned = 0;
  982. int64_t lastWroteStats = 0;
  983. while (s_run) {
  984. //s_peersByIdentity_l.lock();
  985. //s_peersByPhysAddr_l.lock();
  986. //printf("*** have %lu peers at %lu physical endpoints" ZT_EOL_S,(unsigned long)s_peersByIdentity.size(),(unsigned long)s_peersByPhysAddr.size());
  987. //s_peersByPhysAddr_l.unlock();
  988. //s_peersByIdentity_l.unlock();
  989. sleep(1);
  990. const int64_t now = OSUtils::now();
  991. if ((now - lastCleaned) > 120000) {
  992. lastCleaned = now;
  993. // Old multicast subscription cleanup
  994. {
  995. std::lock_guard<std::mutex> l(s_multicastSubscriptions_l);
  996. for(auto a=s_multicastSubscriptions.begin();a!=s_multicastSubscriptions.end();) {
  997. for(auto b=a->second.begin();b!=a->second.end();) {
  998. for(auto c=b->second.begin();c!=b->second.end();) {
  999. if ((now - c->second) > ZT_MULTICAST_LIKE_EXPIRE)
  1000. b->second.erase(c++);
  1001. else ++c;
  1002. }
  1003. if (b->second.empty())
  1004. a->second.erase(b++);
  1005. else ++b;
  1006. }
  1007. if (a->second.empty())
  1008. s_multicastSubscriptions.erase(a++);
  1009. else ++a;
  1010. }
  1011. }
  1012. // Remove expired peers
  1013. {
  1014. std::lock_guard<std::mutex> pbi_l(s_peersByIdentity_l);
  1015. for(auto p=s_peersByIdentity.begin();p!=s_peersByIdentity.end();) {
  1016. if ((now - p->second->lastReceive) > ZT_PEER_ACTIVITY_TIMEOUT) {
  1017. std::lock_guard<std::mutex> pbv_l(s_peersByVirtAddr_l);
  1018. std::lock_guard<std::mutex> pbp_l(s_peersByPhysAddr_l);
  1019. auto pbv = s_peersByVirtAddr.find(p->second->id.address());
  1020. if (pbv != s_peersByVirtAddr.end()) {
  1021. pbv->second.erase(p->second);
  1022. if (pbv->second.empty())
  1023. s_peersByVirtAddr.erase(pbv);
  1024. }
  1025. if (p->second->ip4) {
  1026. auto pbp = s_peersByPhysAddr.find(p->second->ip4);
  1027. if (pbp != s_peersByPhysAddr.end()) {
  1028. pbp->second.erase(p->second);
  1029. if (pbp->second.empty())
  1030. s_peersByPhysAddr.erase(pbp);
  1031. }
  1032. }
  1033. if (p->second->ip6) {
  1034. auto pbp = s_peersByPhysAddr.find(p->second->ip6);
  1035. if (pbp != s_peersByPhysAddr.end()) {
  1036. pbp->second.erase(p->second);
  1037. if (pbp->second.empty())
  1038. s_peersByPhysAddr.erase(pbp);
  1039. }
  1040. }
  1041. s_peersByIdentity.erase(p++);
  1042. } else ++p;
  1043. }
  1044. }
  1045. // Remove old rendezvous and last forwarded tracking entries
  1046. {
  1047. std::lock_guard<std::mutex> l(s_rendezvousTracking_l);
  1048. for(auto lr=s_rendezvousTracking.begin();lr!=s_rendezvousTracking.end();) {
  1049. if ((now - lr->second.ts) > ZT_PEER_ACTIVITY_TIMEOUT)
  1050. s_rendezvousTracking.erase(lr++);
  1051. else ++lr;
  1052. }
  1053. }
  1054. // Remove old last forwarded tracking entries
  1055. {
  1056. std::lock_guard<std::mutex> l(s_lastForwardedTo_l);
  1057. for(auto lf=s_lastForwardedTo.begin();lf!=s_lastForwardedTo.end();) {
  1058. if ((now - lf->second.ts) > ZT_PEER_ACTIVITY_TIMEOUT)
  1059. s_lastForwardedTo.erase(lf++);
  1060. else ++lf;
  1061. }
  1062. }
  1063. }
  1064. // Write stats if configured to do so, and periodically refresh planet file (if any)
  1065. if (((now - lastWroteStats) > 15000)&&(s_statsRoot.length() > 0)) {
  1066. lastWroteStats = now;
  1067. try {
  1068. if (planetFilePath.length() > 0) {
  1069. std::string planetData;
  1070. if ((OSUtils::readFile(planetFilePath.c_str(),planetData))&&(planetData.length() > 0)) {
  1071. std::lock_guard<std::mutex> pl(s_planet_l);
  1072. s_planet = planetData;
  1073. }
  1074. }
  1075. } catch ( ... ) {
  1076. std::lock_guard<std::mutex> pl(s_planet_l);
  1077. s_planet.clear();
  1078. }
  1079. std::string peersFilePath(s_statsRoot);
  1080. peersFilePath.append("/.peers.tmp");
  1081. FILE *pf = fopen(peersFilePath.c_str(),"wb");
  1082. if (pf) {
  1083. std::vector< SharedPtr<RootPeer> > sp;
  1084. {
  1085. std::lock_guard<std::mutex> pbi_l(s_peersByIdentity_l);
  1086. sp.reserve(s_peersByIdentity.size());
  1087. for(auto p=s_peersByIdentity.begin();p!=s_peersByIdentity.end();++p) {
  1088. sp.push_back(p->second);
  1089. }
  1090. }
  1091. std::sort(sp.begin(),sp.end(),[](const SharedPtr<RootPeer> &a,const SharedPtr<RootPeer> &b) { return (a->id < b->id); });
  1092. fprintf(pf,"Address %21s %45s %10s %6s %10s" ZT_EOL_S,"IPv4","IPv6","Age(sec)","Vers","Fwd(KiB/s)");
  1093. {
  1094. std::lock_guard<std::mutex> lf_l(s_lastForwardedTo_l);
  1095. char ip4[128],ip6[128],ver[128];
  1096. for(auto p=sp.begin();p!=sp.end();++p) {
  1097. if ((*p)->ip4) {
  1098. (*p)->ip4.toString(ip4);
  1099. } else {
  1100. ip4[0] = '-';
  1101. ip4[1] = 0;
  1102. }
  1103. if ((*p)->ip6) {
  1104. (*p)->ip6.toString(ip6);
  1105. } else {
  1106. ip6[0] = '-';
  1107. ip6[1] = 0;
  1108. }
  1109. OSUtils::ztsnprintf(ver,sizeof(ver),"%d.%d.%d",(*p)->vMajor,(*p)->vMinor,(*p)->vRev);
  1110. double forwardingSpeed = 0.0;
  1111. auto lft = s_lastForwardedTo.find((*p)->id.address());
  1112. if (lft != s_lastForwardedTo.end())
  1113. forwardingSpeed = lft->second.bps.perSecond(now) / 1024.0;
  1114. fprintf(pf,"%.10llx %21s %45s %10.4f %6s %10.4f" ZT_EOL_S,
  1115. (unsigned long long)(*p)->id.address().toInt(),
  1116. ip4,
  1117. ip6,
  1118. fabs((double)(now - (*p)->lastReceive) / 1000.0),
  1119. ver,
  1120. forwardingSpeed);
  1121. }
  1122. }
  1123. fclose(pf);
  1124. std::string peersFilePath2(s_statsRoot);
  1125. peersFilePath2.append("/peers");
  1126. OSUtils::rm(peersFilePath2);
  1127. OSUtils::rename(peersFilePath.c_str(),peersFilePath2.c_str());
  1128. }
  1129. std::string statsFilePath(s_statsRoot);
  1130. statsFilePath.append("/.stats.tmp");
  1131. FILE *sf = fopen(statsFilePath.c_str(),"wb");
  1132. if (sf) {
  1133. fprintf(sf,"Uptime (seconds) : %ld" ZT_EOL_S,(long)((now - s_startTime) / 1000));
  1134. s_peersByIdentity_l.lock();
  1135. fprintf(sf,"Peers : %llu" ZT_EOL_S,(unsigned long long)s_peersByIdentity.size());
  1136. s_peersByVirtAddr_l.lock();
  1137. fprintf(sf,"Virtual Address Collisions : %llu" ZT_EOL_S,(unsigned long long)(s_peersByIdentity.size() - s_peersByVirtAddr.size()));
  1138. s_peersByVirtAddr_l.unlock();
  1139. s_peersByIdentity_l.unlock();
  1140. s_peersByPhysAddr_l.lock();
  1141. fprintf(sf,"Physical Endpoints : %llu" ZT_EOL_S,(unsigned long long)s_peersByPhysAddr.size());
  1142. s_peersByPhysAddr_l.unlock();
  1143. s_rendezvousTracking_l.lock();
  1144. uint64_t unsuccessfulp2p = 0;
  1145. for(auto lr=s_rendezvousTracking.begin();lr!=s_rendezvousTracking.end();++lr) {
  1146. if (lr->second.count > 6) // 6 == two attempts per edge, one for each direction
  1147. ++unsuccessfulp2p;
  1148. }
  1149. fprintf(sf,"Recent P2P Graph Edges : %llu" ZT_EOL_S,(unsigned long long)s_rendezvousTracking.size());
  1150. if (s_rendezvousTracking.empty()) {
  1151. fprintf(sf,"Recent P2P Success Rate : 100.0000%%" ZT_EOL_S);
  1152. } else {
  1153. fprintf(sf,"Recent P2P Success Rate : %.4f%%" ZT_EOL_S,(1.0 - ((double)unsuccessfulp2p / (double)s_rendezvousTracking.size())) * 100.0);
  1154. }
  1155. s_rendezvousTracking_l.unlock();
  1156. fprintf(sf,"Input (MiB/s) : %.4f" ZT_EOL_S,s_inputRate.perSecond(now) / 1048576.0);
  1157. fprintf(sf,"Output (MiB/s) : %.4f" ZT_EOL_S,s_outputRate.perSecond(now) / 1048576.0);
  1158. fprintf(sf,"Forwarded (MiB/s) : %.4f" ZT_EOL_S,s_forwardRate.perSecond(now) / 1048576.0);
  1159. fprintf(sf,"Discarded Forward (MiB/s) : %.4f" ZT_EOL_S,s_discardedForwardRate.perSecond(now) / 1048576.0);
  1160. fclose(sf);
  1161. std::string statsFilePath2(s_statsRoot);
  1162. statsFilePath2.append("/stats");
  1163. OSUtils::rm(statsFilePath2);
  1164. OSUtils::rename(statsFilePath.c_str(),statsFilePath2.c_str());
  1165. }
  1166. }
  1167. }
  1168. // If we received a kill signal, close everything and wait
  1169. // for threads to die before exiting.
  1170. apiServ.stop();
  1171. for(auto s=sockets.begin();s!=sockets.end();++s) {
  1172. shutdown(*s,SHUT_RDWR);
  1173. close(*s);
  1174. }
  1175. for(auto t=threads.begin();t!=threads.end();++t)
  1176. t->join();
  1177. return 0;
  1178. }