root.cpp 43 KB

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