root.cpp 45 KB

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