root.cpp 46 KB

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