root.cpp 44 KB

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