root.cpp 45 KB

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