root.cpp 43 KB

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