root.cpp 45 KB

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