root.cpp 45 KB

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