root.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377
  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. }
  247. }
  248. if (!peer) {
  249. peer.set(new RootPeer);
  250. peer->identityValidated = false;
  251. if (!s_self.agree(id,peer->key)) {
  252. printf("%s HELLO rejected: key agreement failed" ZT_EOL_S,ip->toString(ipstr));
  253. return;
  254. }
  255. if (!pkt.dearmor(peer->key)) {
  256. printf("%s HELLO rejected: packet authentication failed" ZT_EOL_S,ip->toString(ipstr));
  257. return;
  258. }
  259. if (!pkt.uncompress()) {
  260. printf("%s HELLO rejected: decompression failed" ZT_EOL_S,ip->toString(ipstr));
  261. return;
  262. }
  263. peer->id = id;
  264. peer->lastReceive = now;
  265. {
  266. std::lock_guard<std::mutex> pbv_l(s_peersByVirtAddr_l);
  267. s_peersByVirtAddr[id.address()] = peer;
  268. }
  269. {
  270. std::lock_guard<std::mutex> pl(s_peers_l);
  271. s_peers.emplace_back(peer);
  272. }
  273. {
  274. std::lock_guard<std::mutex> pv(s_peersToValidate_l);
  275. s_peersToValidate.emplace_back(peer);
  276. }
  277. }
  278. }
  279. }
  280. if (!peer) {
  281. {
  282. std::lock_guard<std::mutex> pbv_l(s_peersByVirtAddr_l);
  283. auto p = s_peersByVirtAddr.find(source);
  284. if (p != s_peersByVirtAddr.end()) {
  285. peer = p->second;
  286. }
  287. }
  288. if (peer) {
  289. if (!pkt.dearmor(peer->key)) {
  290. printf("%s HELLO rejected: packet authentication failed" ZT_EOL_S,ip->toString(ipstr));
  291. return;
  292. }
  293. if (!pkt.uncompress()) {
  294. printf("%s packet rejected: decompression failed" ZT_EOL_S,ip->toString(ipstr));
  295. return;
  296. }
  297. } else {
  298. return;
  299. }
  300. }
  301. const int64_t now = OSUtils::now();
  302. if (ip->isV4()) {
  303. peer->ip4 = ip;
  304. peer->v4s = sock;
  305. peer->lastReceiveV4 = now;
  306. if ((now - peer->lastReceiveV6) > ZT_PEER_ACTIVITY_TIMEOUT)
  307. peer->v6s = -1;
  308. } else if (ip->isV6()) {
  309. peer->ip6 = ip;
  310. peer->v6s = sock;
  311. peer->lastReceiveV6 = now;
  312. if ((now - peer->lastReceiveV4) > ZT_PEER_ACTIVITY_TIMEOUT)
  313. peer->v4s = -1;
  314. }
  315. peer->lastReceive = now;
  316. switch(pkt.verb()) {
  317. case Packet::VERB_HELLO:
  318. try {
  319. if ((now - peer->lastHello) > 250) {
  320. peer->lastHello = now;
  321. peer->vProto = (int)pkt[ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION];
  322. peer->vMajor = (int)pkt[ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION];
  323. peer->vMinor = (int)pkt[ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION];
  324. peer->vRev = (int)pkt.template at<uint16_t>(ZT_PROTO_VERB_HELLO_IDX_REVISION);
  325. const uint64_t origId = pkt.packetId();
  326. const uint64_t ts = pkt.template at<uint64_t>(ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP);
  327. pkt.reset(source,s_self.address(),Packet::VERB_OK);
  328. pkt.append((uint8_t)Packet::VERB_HELLO);
  329. pkt.append(origId);
  330. pkt.append(ts);
  331. pkt.append((uint8_t)ZT_PROTO_VERSION);
  332. pkt.append((uint8_t)0);
  333. pkt.append((uint8_t)0);
  334. pkt.append((uint16_t)0);
  335. ip->serialize(pkt);
  336. if (peer->vProto < 20) { // send planet file for pre-2.x peers
  337. std::lock_guard<std::mutex> pl(s_planet_l);
  338. if (s_planet.length() > 0) {
  339. pkt.append((uint16_t)s_planet.size());
  340. pkt.append((const uint8_t *)s_planet.data(),s_planet.size());
  341. }
  342. }
  343. pkt.armor(peer->key,true);
  344. 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)));
  345. s_outputRate.log(now,pkt.size());
  346. peer->lastSend = now;
  347. }
  348. } catch ( ... ) {
  349. printf("* unexpected exception handling HELLO from %s" ZT_EOL_S,ip->toString(ipstr));
  350. }
  351. break;
  352. case Packet::VERB_ECHO:
  353. try {
  354. if ((now - peer->lastEcho) > 500) {
  355. peer->lastEcho = now;
  356. Packet outp(source,s_self.address(),Packet::VERB_OK);
  357. outp.append((uint8_t)Packet::VERB_ECHO);
  358. outp.append(pkt.packetId());
  359. outp.append(((const uint8_t *)pkt.data()) + ZT_PACKET_IDX_PAYLOAD,pkt.size() - ZT_PACKET_IDX_PAYLOAD);
  360. outp.compress();
  361. outp.armor(peer->key,true);
  362. 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)));
  363. s_outputRate.log(now,outp.size());
  364. peer->lastSend = now;
  365. }
  366. } catch ( ... ) {
  367. printf("* unexpected exception handling ECHO from %s" ZT_EOL_S,ip->toString(ipstr));
  368. }
  369. case Packet::VERB_WHOIS:
  370. try {
  371. std::vector< SharedPtr<RootPeer> > results;
  372. results.reserve(4);
  373. {
  374. std::lock_guard<std::mutex> l(s_peersByVirtAddr_l);
  375. for(unsigned int ptr=ZT_PACKET_IDX_PAYLOAD;(ptr+ZT_ADDRESS_LENGTH)<=pkt.size();ptr+=ZT_ADDRESS_LENGTH) {
  376. auto p = s_peersByVirtAddr.find(Address(pkt.field(ptr,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH));
  377. if (p != s_peersByVirtAddr.end()) {
  378. results.push_back(p->second);
  379. }
  380. }
  381. }
  382. if (!results.empty()) {
  383. const uint64_t origId = pkt.packetId();
  384. pkt.reset(source,s_self.address(),Packet::VERB_OK);
  385. pkt.append((uint8_t)Packet::VERB_WHOIS);
  386. pkt.append(origId);
  387. for(auto p=results.begin();p!=results.end();++p)
  388. (*p)->id.serialize(pkt,false);
  389. pkt.armor(peer->key,true);
  390. 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)));
  391. s_outputRate.log(now,pkt.size());
  392. peer->lastSend = now;
  393. }
  394. } catch ( ... ) {
  395. printf("* unexpected exception handling ECHO from %s" ZT_EOL_S,ip->toString(ipstr));
  396. }
  397. case Packet::VERB_MULTICAST_LIKE:
  398. try {
  399. std::lock_guard<std::mutex> l(s_multicastSubscriptions_l);
  400. for(unsigned int ptr=ZT_PACKET_IDX_PAYLOAD;(ptr+18)<=pkt.size();ptr+=18) {
  401. const uint64_t nwid = pkt.template at<uint64_t>(ptr);
  402. const MulticastGroup mg(MAC(pkt.field(ptr + 8,6),6),pkt.template at<uint32_t>(ptr + 14));
  403. s_multicastSubscriptions[nwid][mg][source] = now;
  404. }
  405. } catch ( ... ) {
  406. printf("* unexpected exception handling MULTICAST_LIKE from %s" ZT_EOL_S,ip->toString(ipstr));
  407. }
  408. break;
  409. case Packet::VERB_MULTICAST_GATHER:
  410. try {
  411. const uint64_t nwid = pkt.template at<uint64_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID);
  412. //const unsigned int flags = pkt[ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS];
  413. 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));
  414. unsigned int gatherLimit = pkt.template at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_GATHER_LIMIT);
  415. if (gatherLimit > 255)
  416. gatherLimit = 255;
  417. const uint64_t origId = pkt.packetId();
  418. pkt.reset(source,s_self.address(),Packet::VERB_OK);
  419. pkt.append((uint8_t)Packet::VERB_MULTICAST_GATHER);
  420. pkt.append(origId);
  421. pkt.append(nwid);
  422. mg.mac().appendTo(pkt);
  423. pkt.append((uint32_t)mg.adi());
  424. {
  425. std::lock_guard<std::mutex> l(s_multicastSubscriptions_l);
  426. auto forNet = s_multicastSubscriptions.find(nwid);
  427. if (forNet != s_multicastSubscriptions.end()) {
  428. auto forGroup = forNet->second.find(mg);
  429. if (forGroup != forNet->second.end()) {
  430. pkt.append((uint32_t)forGroup->second.size());
  431. const unsigned int countAt = pkt.size();
  432. pkt.addSize(2);
  433. unsigned int l = 0;
  434. for(auto g=forGroup->second.begin();((l<gatherLimit)&&(g!=forGroup->second.end()));++g) {
  435. if (g->first != source) {
  436. ++l;
  437. g->first.appendTo(pkt);
  438. }
  439. }
  440. if (l > 0) {
  441. pkt.setAt<uint16_t>(countAt,(uint16_t)l);
  442. pkt.armor(peer->key,true);
  443. sendto(sock,pkt.data(),pkt.size(),SENDTO_FLAGS,(const struct sockaddr *)ip,(socklen_t)(ip->isV4() ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6)));
  444. s_outputRate.log(now,pkt.size());
  445. peer->lastSend = now;
  446. }
  447. }
  448. }
  449. }
  450. } catch ( ... ) {
  451. printf("* unexpected exception handling MULTICAST_GATHER from %s" ZT_EOL_S,ip->toString(ipstr));
  452. }
  453. break;
  454. default:
  455. break;
  456. }
  457. return;
  458. }
  459. // If we made it here, we are forwarding this packet to someone else and also possibly
  460. // sending a RENDEZVOUS message.
  461. int hops = 0;
  462. bool introduce = false;
  463. if (fragment) {
  464. if ((hops = (int)reinterpret_cast<Packet::Fragment *>(&pkt)->incrementHops()) > s_relayMaxHops) {
  465. //printf("%s refused to forward to %s: max hop count exceeded" ZT_EOL_S,ip->toString(ipstr),dest.toString(astr));
  466. s_discardedForwardRate.log(now,pkt.size());
  467. return;
  468. }
  469. } else {
  470. if ((hops = (int)pkt.incrementHops()) > s_relayMaxHops) {
  471. //printf("%s refused to forward to %s: max hop count exceeded" ZT_EOL_S,ip->toString(ipstr),dest.toString(astr));
  472. s_discardedForwardRate.log(now,pkt.size());
  473. return;
  474. }
  475. if (hops == 1) {
  476. RendezvousKey rk(source,dest);
  477. std::lock_guard<std::mutex> l(s_rendezvousTracking_l);
  478. RendezvousStats &lr = s_rendezvousTracking[rk];
  479. if ((now - lr.ts) >= 30000) {
  480. ++lr.count;
  481. lr.ts = now;
  482. introduce = true;
  483. }
  484. }
  485. }
  486. std::pair< InetAddress,SharedPtr<RootPeer> > forwardTo;
  487. {
  488. std::lock_guard<std::mutex> pbv_l(s_peersByVirtAddr_l);
  489. auto p = s_peersByVirtAddr.find(dest);
  490. if (p != s_peersByVirtAddr.end()) {
  491. if ((p->second->v4s >= 0)&&(p->second->v6s >= 0)) {
  492. if (p->second->lastReceiveV4 > p->second->lastReceiveV6) {
  493. forwardTo = std::pair< InetAddress,SharedPtr<RootPeer> >(p->second->ip4,p->second);
  494. } else {
  495. forwardTo = std::pair< InetAddress,SharedPtr<RootPeer> >(p->second->ip6,p->second);
  496. }
  497. } else if (p->second->v4s >= 0) {
  498. forwardTo = std::pair< InetAddress,SharedPtr<RootPeer> >(p->second->ip4,p->second);
  499. } else if (p->second->v6s >= 0) {
  500. forwardTo = std::pair< InetAddress,SharedPtr<RootPeer> >(p->second->ip6,p->second);
  501. }
  502. }
  503. }
  504. if (unlikely(!forwardTo.second)) {
  505. s_discardedForwardRate.log(now,pkt.size());
  506. return;
  507. }
  508. if (introduce) {
  509. std::lock_guard<std::mutex> l(s_peersByVirtAddr_l);
  510. auto sp = s_peersByVirtAddr.find(source);
  511. if ((sp->second->v6s >= 0)&&(forwardTo.second->v6s >= 0)) {
  512. Packet outp(source,s_self.address(),Packet::VERB_RENDEZVOUS);
  513. outp.append((uint8_t)0);
  514. dest.appendTo(outp);
  515. outp.append((uint16_t)sp->second->ip6.port());
  516. outp.append((uint8_t)16);
  517. outp.append((const uint8_t *)(sp->second->ip6.rawIpData()),16);
  518. outp.armor(forwardTo.second->key,true);
  519. sendto(forwardTo.second->v6s,outp.data(),outp.size(),SENDTO_FLAGS,(const struct sockaddr *)&forwardTo.first,(socklen_t)sizeof(struct sockaddr_in6));
  520. s_outputRate.log(now,outp.size());
  521. forwardTo.second->lastSend = now;
  522. outp.reset(dest,s_self.address(),Packet::VERB_RENDEZVOUS);
  523. outp.append((uint8_t)0);
  524. source.appendTo(outp);
  525. outp.append((uint16_t)forwardTo.first.port());
  526. outp.append((uint8_t)16);
  527. outp.append((const uint8_t *)(forwardTo.first.rawIpData()),16);
  528. outp.armor(sp->second->key,true);
  529. sendto(sp->second->v6s,outp.data(),outp.size(),SENDTO_FLAGS,(const struct sockaddr *)&(sp->second->ip6),(socklen_t)sizeof(struct sockaddr_in6));
  530. s_outputRate.log(now,outp.size());
  531. sp->second->lastSend = now;
  532. }
  533. if ((sp->second->v4s >= 0)&&(forwardTo.second->v4s >= 0)) {
  534. Packet outp(source,s_self.address(),Packet::VERB_RENDEZVOUS);
  535. outp.append((uint8_t)0);
  536. dest.appendTo(outp);
  537. outp.append((uint16_t)sp->second->ip4.port());
  538. outp.append((uint8_t)4);
  539. outp.append((const uint8_t *)sp->second->ip4.rawIpData(),4);
  540. outp.armor(forwardTo.second->key,true);
  541. sendto(forwardTo.second->v4s,outp.data(),outp.size(),SENDTO_FLAGS,(const struct sockaddr *)&forwardTo.first,(socklen_t)sizeof(struct sockaddr_in));
  542. s_outputRate.log(now,outp.size());
  543. forwardTo.second->lastSend = now;
  544. outp.reset(dest,s_self.address(),Packet::VERB_RENDEZVOUS);
  545. outp.append((uint8_t)0);
  546. source.appendTo(outp);
  547. outp.append((uint16_t)forwardTo.first.port());
  548. outp.append((uint8_t)4);
  549. outp.append((const uint8_t *)(forwardTo.first.rawIpData()),4);
  550. outp.armor(sp->second->key,true);
  551. sendto(sp->second->v6s,outp.data(),outp.size(),SENDTO_FLAGS,(const struct sockaddr *)&(sp->second->ip4),(socklen_t)sizeof(struct sockaddr_in));
  552. s_outputRate.log(now,outp.size());
  553. sp->second->lastSend = now;
  554. }
  555. }
  556. if (sendto(forwardTo.first.isV4() ? forwardTo.second->v4s : forwardTo.second->v6s,pkt.data(),pkt.size(),SENDTO_FLAGS,(const struct sockaddr *)&forwardTo.first,(socklen_t)(forwardTo.first.isV4() ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6))) > 0) {
  557. s_outputRate.log(now,pkt.size());
  558. s_forwardRate.log(now,pkt.size());
  559. forwardTo.second->lastSend = now;
  560. }
  561. }
  562. //////////////////////////////////////////////////////////////////////////////
  563. //////////////////////////////////////////////////////////////////////////////
  564. static int bindSocket(struct sockaddr *const bindAddr)
  565. {
  566. const int s = socket(bindAddr->sa_family,SOCK_DGRAM,0);
  567. if (s < 0) {
  568. close(s);
  569. return -1;
  570. }
  571. int f = 16777216;
  572. while (f > 65536) {
  573. if (setsockopt(s,SOL_SOCKET,SO_RCVBUF,(const char *)&f,sizeof(f)) == 0)
  574. break;
  575. f -= 65536;
  576. }
  577. f = 16777216;
  578. while (f > 65536) {
  579. if (setsockopt(s,SOL_SOCKET,SO_SNDBUF,(const char *)&f,sizeof(f)) == 0)
  580. break;
  581. f -= 65536;
  582. }
  583. if (bindAddr->sa_family == AF_INET6) {
  584. f = 1; setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f));
  585. #ifdef IPV6_MTU_DISCOVER
  586. f = 0; setsockopt(s,IPPROTO_IPV6,IPV6_MTU_DISCOVER,&f,sizeof(f));
  587. #endif
  588. #ifdef IPV6_DONTFRAG
  589. f = 0; setsockopt(s,IPPROTO_IPV6,IPV6_DONTFRAG,&f,sizeof(f));
  590. #endif
  591. }
  592. #ifdef IP_DONTFRAG
  593. f = 0; setsockopt(s,IPPROTO_IP,IP_DONTFRAG,&f,sizeof(f));
  594. #endif
  595. #ifdef IP_MTU_DISCOVER
  596. f = IP_PMTUDISC_DONT; setsockopt(s,IPPROTO_IP,IP_MTU_DISCOVER,&f,sizeof(f));
  597. #endif
  598. /*
  599. #ifdef SO_NO_CHECK
  600. if (bindAddr->sa_family == AF_INET) {
  601. f = 1; setsockopt(s,SOL_SOCKET,SO_NO_CHECK,(void *)&f,sizeof(f));
  602. }
  603. #endif
  604. */
  605. #ifdef SO_REUSEPORT
  606. f = 1; setsockopt(s,SOL_SOCKET,SO_REUSEPORT,(void *)&f,sizeof(f));
  607. #endif
  608. #ifndef __LINUX__ // linux wants just SO_REUSEPORT
  609. f = 1; setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  610. #endif
  611. #ifdef __LINUX__
  612. struct timeval tv;
  613. tv.tv_sec = 1;
  614. tv.tv_usec = 0;
  615. setsockopt(s,SOL_SOCKET,SO_RCVTIMEO,(const void *)&tv,sizeof(tv));
  616. #endif
  617. if (bind(s,bindAddr,(bindAddr->sa_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6))) {
  618. close(s);
  619. //printf("%s\n",strerror(errno));
  620. return -1;
  621. }
  622. return s;
  623. }
  624. static void shutdownSigHandler(int sig)
  625. {
  626. s_run = false;
  627. }
  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. threads.push_back(std::thread([]() {
  788. std::vector< SharedPtr<RootPeer> > toValidate;
  789. while (s_run) {
  790. {
  791. std::lock_guard<std::mutex> l(s_peersToValidate_l);
  792. toValidate.swap(s_peersToValidate);
  793. }
  794. for(auto p=toValidate.begin();p!=toValidate.end();++p) {
  795. if (likely(!(*p)->identityValidated)) {
  796. if (likely((*p)->id.locallyValidate())) {
  797. (*p)->identityValidated = true;
  798. } else {
  799. {
  800. std::lock_guard<std::mutex> p_l(s_peersByVirtAddr_l);
  801. auto pp = s_peersByVirtAddr.find((*p)->id.address());
  802. if ((pp != s_peersByVirtAddr.end())&&(pp->second == *p)) {
  803. s_peersByVirtAddr.erase(pp);
  804. }
  805. }
  806. {
  807. std::lock_guard<std::mutex> p_l(s_peers_l);
  808. for(auto pp=s_peers.begin();pp!=s_peers.end();++pp) {
  809. if (*p == *pp) {
  810. s_peers.erase(pp);
  811. break;
  812. }
  813. }
  814. }
  815. }
  816. }
  817. }
  818. toValidate.clear();
  819. usleep(1000);
  820. }
  821. }));
  822. for(auto port=s_ports.begin();port!=s_ports.end();++port) {
  823. for(unsigned int tn=0;tn<ncores;++tn) {
  824. struct sockaddr_in6 in6;
  825. memset(&in6,0,sizeof(in6));
  826. in6.sin6_family = AF_INET6;
  827. in6.sin6_port = htons((uint16_t)*port);
  828. const int s6 = bindSocket((struct sockaddr *)&in6);
  829. if (s6 < 0) {
  830. std::cout << "ERROR: unable to bind to port " << *port << ZT_EOL_S;
  831. exit(1);
  832. }
  833. struct sockaddr_in in4;
  834. memset(&in4,0,sizeof(in4));
  835. in4.sin_family = AF_INET;
  836. in4.sin_port = htons((uint16_t)*port);
  837. const int s4 = bindSocket((struct sockaddr *)&in4);
  838. if (s4 < 0) {
  839. std::cout << "ERROR: unable to bind to port " << *port << ZT_EOL_S;
  840. exit(1);
  841. }
  842. sockets.push_back(s6);
  843. sockets.push_back(s4);
  844. if (v4Sock < 0) v4Sock = s4;
  845. if (v6Sock < 0) v6Sock = s6;
  846. threads.push_back(std::thread([s6,s4]() {
  847. struct sockaddr_in6 in6;
  848. Packet *pkt = new Packet();
  849. for(;;) {
  850. memset(&in6,0,sizeof(in6));
  851. socklen_t sl = sizeof(in6);
  852. const int pl = (int)recvfrom(s6,pkt->unsafeData(),pkt->capacity(),RECVFROM_FLAGS,(struct sockaddr *)&in6,&sl);
  853. if (pl > 0) {
  854. if ((pl >= ZT_PROTO_MIN_FRAGMENT_LENGTH)&&(pl <= ZT_PROTO_MAX_PACKET_LENGTH)) {
  855. try {
  856. pkt->setSize((unsigned int)pl);
  857. handlePacket(s6,reinterpret_cast<const InetAddress *>(&in6),*pkt);
  858. } catch (std::exception &exc) {
  859. char ipstr[128];
  860. printf("WARNING: unexpected exception handling packet from %s: %s" ZT_EOL_S,reinterpret_cast<const InetAddress *>(&in6)->toString(ipstr),exc.what());
  861. } catch (int exc) {
  862. char ipstr[128];
  863. printf("WARNING: unexpected exception handling packet from %s: ZT exception code %d" ZT_EOL_S,reinterpret_cast<const InetAddress *>(&in6)->toString(ipstr),exc);
  864. } catch ( ... ) {
  865. char ipstr[128];
  866. printf("WARNING: unexpected exception handling packet from %s: unknown exception" ZT_EOL_S,reinterpret_cast<const InetAddress *>(&in6)->toString(ipstr));
  867. }
  868. }
  869. } else if (!s_run) {
  870. break;
  871. }
  872. }
  873. delete pkt;
  874. }));
  875. threads.push_back(std::thread([s6,s4]() {
  876. struct sockaddr_in in4;
  877. Packet *pkt = new Packet();
  878. for(;;) {
  879. memset(&in4,0,sizeof(in4));
  880. socklen_t sl = sizeof(in4);
  881. const int pl = (int)recvfrom(s4,pkt->unsafeData(),pkt->capacity(),RECVFROM_FLAGS,(struct sockaddr *)&in4,&sl);
  882. if (pl > 0) {
  883. if ((pl >= ZT_PROTO_MIN_FRAGMENT_LENGTH)&&(pl <= ZT_PROTO_MAX_PACKET_LENGTH)) {
  884. try {
  885. pkt->setSize((unsigned int)pl);
  886. handlePacket(s4,reinterpret_cast<const InetAddress *>(&in4),*pkt);
  887. } catch (std::exception &exc) {
  888. char ipstr[128];
  889. printf("WARNING: unexpected exception handling packet from %s: %s" ZT_EOL_S,reinterpret_cast<const InetAddress *>(&in4)->toString(ipstr),exc.what());
  890. } catch (int exc) {
  891. char ipstr[128];
  892. printf("WARNING: unexpected exception handling packet from %s: ZT exception code %d" ZT_EOL_S,reinterpret_cast<const InetAddress *>(&in4)->toString(ipstr),exc);
  893. } catch ( ... ) {
  894. char ipstr[128];
  895. printf("WARNING: unexpected exception handling packet from %s: unknown exception" ZT_EOL_S,reinterpret_cast<const InetAddress *>(&in4)->toString(ipstr));
  896. }
  897. }
  898. } else if (!s_run) {
  899. break;
  900. }
  901. }
  902. delete pkt;
  903. }));
  904. }
  905. }
  906. // A minimal read-only local API for monitoring and status queries
  907. httplib::Server apiServ;
  908. threads.push_back(std::thread([&apiServ,httpPort]() {
  909. // Human readable status page
  910. apiServ.Get("/",[](const httplib::Request &req,httplib::Response &res) {
  911. std::ostringstream o;
  912. o << "ZeroTier Root Server " << ZEROTIER_ONE_VERSION_MAJOR << '.' << ZEROTIER_ONE_VERSION_MINOR << '.' << ZEROTIER_ONE_VERSION_REVISION << ZT_EOL_S;
  913. o << "(c)2019 ZeroTier, Inc." ZT_EOL_S "Licensed under the ZeroTier BSL 1.1" ZT_EOL_S ZT_EOL_S;
  914. s_peersByVirtAddr_l.lock();
  915. o << "Peers Online: " << s_peersByVirtAddr.size() << ZT_EOL_S;
  916. s_peersByVirtAddr_l.unlock();
  917. res.set_content(o.str(),"text/plain");
  918. });
  919. apiServ.Get("/metrics",[](const httplib::Request &req, httplib::Response &res) {
  920. std::ostringstream o;
  921. int64_t now = OSUtils::now();
  922. char buf[11];
  923. const char *root_id = s_self.address().toString(buf);
  924. o << "# HELP root_peers_online Number of active peers online" << ZT_EOL_S;
  925. o << "# TYPE root_peers_online gauge" << ZT_EOL_S;
  926. s_peersByVirtAddr_l.lock();
  927. o << "root_peers_online{root_id=\"" << root_id << "\"} " << s_peersByVirtAddr.size() << ZT_EOL_S;
  928. s_peersByVirtAddr_l.unlock();
  929. o << "# HELP root_input_rate Input rate MiB/s" << ZT_EOL_S;
  930. o << "# TYPE root_input_rate gauge" << ZT_EOL_S;
  931. o << "root_input_rate{root_id=\"" << root_id << "\"} " << std::setprecision(5) << (s_inputRate.perSecond(now)/1048576.0) << ZT_EOL_S;
  932. o << "# HELP root_output_rate Output rate MiB/s" << ZT_EOL_S;
  933. o << "# TYPE root_output_rate gauge" << ZT_EOL_S;
  934. o << "root_output_rate{root_id=\"" << root_id << "\"} " << std::setprecision(5) << (s_outputRate.perSecond(now)/1048576.0) << ZT_EOL_S;
  935. o << "# HELP root_forwarded_rate Forwarded packet rate MiB/s" << ZT_EOL_S;
  936. o << "# TYPE root_forwarded_rate gauge" << ZT_EOL_S;
  937. o << "root_forwarded_rate{root_id=\"" << root_id << "\"} " << std::setprecision(5) << (s_forwardRate.perSecond(now)/1048576.0) << ZT_EOL_S;
  938. o << "# HELP root_discarded_rate Discarded forwards MiB/s" << ZT_EOL_S;
  939. o << "# TYPE root_discarded_rate gauge" << ZT_EOL_S;
  940. o << "root_discarded_rate{root_id=\"" << root_id << "\"} " << std::setprecision(5) << (s_discardedForwardRate.perSecond(now)/1048576.0) << ZT_EOL_S;
  941. res.set_content(o.str(), "text/plain");
  942. });
  943. // Peer list for compatibility with software that monitors regular nodes
  944. apiServ.Get("/peer",[](const httplib::Request &req,httplib::Response &res) {
  945. char tmp[256];
  946. std::ostringstream o;
  947. o << '[';
  948. try {
  949. bool first = true;
  950. std::lock_guard<std::mutex> l(s_peers_l);
  951. for(auto p=s_peers.begin();p!=s_peers.end();++p) {
  952. if (first)
  953. first = false;
  954. else o << ',';
  955. o <<
  956. "{\"address\":\"" << (*p)->id.address().toString(tmp) << "\""
  957. ",\"latency\":-1"
  958. ",\"paths\":[";
  959. if ((*p)->v4s >= 0) {
  960. o <<
  961. "{\"active\":true"
  962. ",\"address\":\"" << (*p)->ip4.toIpString(tmp) << "\\/" << (*p)->ip4.port() << "\""
  963. ",\"expired\":false"
  964. ",\"lastReceive\":" << (*p)->lastReceive <<
  965. ",\"lastSend\":" << (*p)->lastSend <<
  966. ",\"preferred\":true"
  967. ",\"trustedPathId\":0}";
  968. }
  969. if ((*p)->v6s >= 0) {
  970. if ((*p)->v4s >= 0)
  971. o << ',';
  972. o <<
  973. "{\"active\":true"
  974. ",\"address\":\"" << (*p)->ip6.toIpString(tmp) << "\\/" << (*p)->ip6.port() << "\""
  975. ",\"expired\":false"
  976. ",\"lastReceive\":" << (*p)->lastReceive <<
  977. ",\"lastSend\":" << (*p)->lastSend <<
  978. ",\"preferred\":" << (((*p)->ip4) ? "false" : "true") <<
  979. ",\"trustedPathId\":0}";
  980. }
  981. o << "]"
  982. ",\"role\":\"LEAF\""
  983. ",\"version\":\"" << (*p)->vMajor << '.' << (*p)->vMinor << '.' << (*p)->vRev << "\""
  984. ",\"versionMajor\":" << (*p)->vMajor <<
  985. ",\"versionMinor\":" << (*p)->vMinor <<
  986. ",\"versionRev\":" << (*p)->vRev << "}";
  987. }
  988. } catch ( ... ) {}
  989. o << ']';
  990. res.set_content(o.str(),"application/json");
  991. });
  992. // GeoIP map if enabled
  993. apiServ.Get("/map",[](const httplib::Request &req,httplib::Response &res) {
  994. char tmp[4096];
  995. if (!s_geoInit) {
  996. res.set_content("Not enabled or GeoIP CSV file not finished reading.","text/plain");
  997. return;
  998. }
  999. std::ostringstream o;
  1000. o << ZT_GEOIP_HTML_HEAD;
  1001. try {
  1002. bool firstCoord = true;
  1003. std::pair< uint32_t,uint32_t > k4(0,0xffffffff);
  1004. std::pair< std::array< uint64_t,2 >,std::array< uint64_t,2 > > k6;
  1005. k6.second[0] = 0xffffffffffffffffULL; k6.second[1] = 0xffffffffffffffffULL;
  1006. std::unordered_map< InetAddress,std::set<Address>,InetAddressHasher > ips;
  1007. {
  1008. std::lock_guard<std::mutex> l(s_peers_l);
  1009. for(auto p=s_peers.begin();p!=s_peers.end();++p) {
  1010. if ((*p)->v4s >= 0)
  1011. ips[(*p)->ip4].insert((*p)->id.address());
  1012. if ((*p)->v6s >= 0)
  1013. ips[(*p)->ip6].insert((*p)->id.address());
  1014. }
  1015. }
  1016. for(auto p=ips.begin();p!=ips.end();++p) {
  1017. if (p->first.isV4()) {
  1018. k4.first = ip4ToH32(p->first);
  1019. auto geo = std::map< std::pair< uint32_t,uint32_t >,std::pair< float,float > >::reverse_iterator(s_geoIp4.upper_bound(k4));
  1020. uint32_t bestRangeSize = 0xffffffff;
  1021. std::pair< float,float > bestRangeLatLon;
  1022. while (geo != s_geoIp4.rend()) {
  1023. if ((geo->first.first <= k4.first)&&(geo->first.second >= k4.first)) {
  1024. uint32_t range = geo->first.second - geo->first.first;
  1025. if (range <= bestRangeSize) {
  1026. bestRangeSize = range;
  1027. bestRangeLatLon = geo->second;
  1028. }
  1029. } else if ((geo->first.first < k4.first)&&(geo->first.second < k4.first)) {
  1030. break;
  1031. }
  1032. ++geo;
  1033. }
  1034. if (bestRangeSize != 0xffffffff) {
  1035. if (!firstCoord)
  1036. o << ',';
  1037. firstCoord = false;
  1038. o << "{lat:" << bestRangeLatLon.first << ",lng:" << bestRangeLatLon.second << ",_l:\"";
  1039. bool firstAddr = true;
  1040. for(auto a=p->second.begin();a!=p->second.end();++a) {
  1041. if (!firstAddr)
  1042. o << ',';
  1043. o << a->toString(tmp);
  1044. firstAddr = false;
  1045. }
  1046. o << "\"}";
  1047. }
  1048. } else if (p->first.isV6()) {
  1049. k6.first = ip6ToH128(p->first);
  1050. 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));
  1051. while (geo != s_geoIp6.rend()) {
  1052. if ((geo->first.first <= k6.first)&&(geo->first.second >= k6.first)) {
  1053. if (!firstCoord)
  1054. o << ',';
  1055. firstCoord = false;
  1056. o << "{lat:" << geo->second.first << ",lng:" << geo->second.second << ",_l:\"";
  1057. bool firstAddr = true;
  1058. for(auto a=p->second.begin();a!=p->second.end();++a) {
  1059. if (!firstAddr)
  1060. o << ',';
  1061. o << a->toString(tmp);
  1062. firstAddr = false;
  1063. }
  1064. o << "\"}";
  1065. break;
  1066. } else if ((geo->first.first < k6.first)&&(geo->first.second < k6.first)) {
  1067. break;
  1068. }
  1069. ++geo;
  1070. }
  1071. }
  1072. }
  1073. } catch ( ... ) {
  1074. res.set_content("Internal error: unexpected exception resolving GeoIP locations","text/plain");
  1075. return;
  1076. }
  1077. OSUtils::ztsnprintf(tmp,sizeof(tmp),ZT_GEOIP_HTML_TAIL,s_googleMapsAPIKey.c_str());
  1078. o << tmp;
  1079. res.set_content(o.str(),"text/html");
  1080. });
  1081. apiServ.listen("127.0.0.1",httpPort,0);
  1082. }));
  1083. // In the main thread periodically clean stuff up
  1084. int64_t lastCleaned = 0;
  1085. int64_t lastWroteStats = 0;
  1086. while (s_run) {
  1087. sleep(1);
  1088. const int64_t now = OSUtils::now();
  1089. if ((now - lastCleaned) > 300000) {
  1090. lastCleaned = now;
  1091. // Old multicast subscription cleanup
  1092. {
  1093. std::lock_guard<std::mutex> l(s_multicastSubscriptions_l);
  1094. for(auto a=s_multicastSubscriptions.begin();a!=s_multicastSubscriptions.end();) {
  1095. for(auto b=a->second.begin();b!=a->second.end();) {
  1096. for(auto c=b->second.begin();c!=b->second.end();) {
  1097. if ((now - c->second) > ZT_MULTICAST_LIKE_EXPIRE)
  1098. b->second.erase(c++);
  1099. else ++c;
  1100. }
  1101. if (b->second.empty())
  1102. a->second.erase(b++);
  1103. else ++b;
  1104. }
  1105. if (a->second.empty())
  1106. s_multicastSubscriptions.erase(a++);
  1107. else ++a;
  1108. }
  1109. }
  1110. try {
  1111. std::vector< SharedPtr<RootPeer> > toRemove;
  1112. toRemove.reserve(1024);
  1113. {
  1114. std::lock_guard<std::mutex> pbi_l(s_peers_l);
  1115. std::vector< SharedPtr<RootPeer> > newPeers;
  1116. newPeers.reserve(s_peers.size());
  1117. for(auto p=s_peers.begin();p!=s_peers.end();++p) {
  1118. if ((now - (*p)->lastReceive) > ZT_PEER_ACTIVITY_TIMEOUT) {
  1119. toRemove.emplace_back();
  1120. p->swap(toRemove.back());
  1121. } else {
  1122. newPeers.emplace_back();
  1123. p->swap(newPeers.back());
  1124. }
  1125. }
  1126. newPeers.swap(s_peers);
  1127. }
  1128. for(auto p=toRemove.begin();p!=toRemove.end();++p) {
  1129. {
  1130. std::lock_guard<std::mutex> pbv_l(s_peersByVirtAddr_l);
  1131. auto pbv = s_peersByVirtAddr.find((*p)->id.address());
  1132. if ((pbv != s_peersByVirtAddr.end())&&(pbv->second == *p)) {
  1133. s_peersByVirtAddr.erase(pbv);
  1134. }
  1135. }
  1136. }
  1137. } catch ( ... ) {}
  1138. // Remove old rendezvous entries
  1139. {
  1140. std::lock_guard<std::mutex> l(s_rendezvousTracking_l);
  1141. for(auto lr=s_rendezvousTracking.begin();lr!=s_rendezvousTracking.end();) {
  1142. if ((now - lr->second.ts) > ZT_PEER_ACTIVITY_TIMEOUT)
  1143. s_rendezvousTracking.erase(lr++);
  1144. else ++lr;
  1145. }
  1146. }
  1147. }
  1148. // Write stats if configured to do so, and periodically refresh planet file (if any)
  1149. if (((now - lastWroteStats) > 15000)&&(s_statsRoot.length() > 0)) {
  1150. lastWroteStats = now;
  1151. try {
  1152. if (planetFilePath.length() > 0) {
  1153. std::string planetData;
  1154. if ((OSUtils::readFile(planetFilePath.c_str(),planetData))&&(planetData.length() > 0)) {
  1155. std::lock_guard<std::mutex> pl(s_planet_l);
  1156. s_planet = planetData;
  1157. }
  1158. }
  1159. } catch ( ... ) {
  1160. std::lock_guard<std::mutex> pl(s_planet_l);
  1161. s_planet.clear();
  1162. }
  1163. std::string peersFilePath(s_statsRoot);
  1164. peersFilePath.append("/.peers.tmp");
  1165. FILE *pf = fopen(peersFilePath.c_str(),"wb");
  1166. if (pf) {
  1167. std::vector< SharedPtr<RootPeer> > sp;
  1168. {
  1169. std::lock_guard<std::mutex> pbi_l(s_peers_l);
  1170. sp.reserve(s_peers.size());
  1171. for(auto p=s_peers.begin();p!=s_peers.end();++p) {
  1172. sp.emplace_back(*p);
  1173. }
  1174. }
  1175. std::sort(sp.begin(),sp.end(),[](const SharedPtr<RootPeer> &a,const SharedPtr<RootPeer> &b) { return (a->id < b->id); });
  1176. fprintf(pf,"Address %21s %45s %10s %6s %10s" ZT_EOL_S,"IPv4","IPv6","Age(sec)","Vers","Fwd(KiB/s)");
  1177. {
  1178. char ip4[128],ip6[128],ver[128];
  1179. for(auto p=sp.begin();p!=sp.end();++p) {
  1180. if ((*p)->v4s >= 0) {
  1181. (*p)->ip4.toString(ip4);
  1182. } else {
  1183. ip4[0] = '-';
  1184. ip4[1] = 0;
  1185. }
  1186. if ((*p)->v6s >= 0) {
  1187. (*p)->ip6.toString(ip6);
  1188. } else {
  1189. ip6[0] = '-';
  1190. ip6[1] = 0;
  1191. }
  1192. OSUtils::ztsnprintf(ver,sizeof(ver),"%d.%d.%d",(*p)->vMajor,(*p)->vMinor,(*p)->vRev);
  1193. fprintf(pf,"%.10llx %21s %45s %10.4f %6s" ZT_EOL_S,
  1194. (unsigned long long)(*p)->id.address().toInt(),
  1195. ip4,
  1196. ip6,
  1197. fabs((double)(now - (*p)->lastReceive) / 1000.0),
  1198. ver);
  1199. }
  1200. }
  1201. fclose(pf);
  1202. std::string peersFilePath2(s_statsRoot);
  1203. peersFilePath2.append("/peers");
  1204. OSUtils::rm(peersFilePath2);
  1205. OSUtils::rename(peersFilePath.c_str(),peersFilePath2.c_str());
  1206. }
  1207. std::string statsFilePath(s_statsRoot);
  1208. statsFilePath.append("/.stats.tmp");
  1209. FILE *sf = fopen(statsFilePath.c_str(),"wb");
  1210. if (sf) {
  1211. fprintf(sf,"Uptime (seconds) : %ld" ZT_EOL_S,(long)((now - s_startTime) / 1000));
  1212. s_peersByVirtAddr_l.lock();
  1213. fprintf(sf,"Peers : %llu" ZT_EOL_S,(unsigned long long)s_peersByVirtAddr.size());
  1214. s_peersByVirtAddr_l.unlock();
  1215. s_rendezvousTracking_l.lock();
  1216. uint64_t unsuccessfulp2p = 0;
  1217. for(auto lr=s_rendezvousTracking.begin();lr!=s_rendezvousTracking.end();++lr) {
  1218. if (lr->second.count > 6) // 6 == two attempts per edge, one for each direction
  1219. ++unsuccessfulp2p;
  1220. }
  1221. fprintf(sf,"Recent P2P Graph Edges : %llu" ZT_EOL_S,(unsigned long long)s_rendezvousTracking.size());
  1222. if (s_rendezvousTracking.empty()) {
  1223. fprintf(sf,"Recent P2P Success Rate : 100.0000%%" ZT_EOL_S);
  1224. } else {
  1225. fprintf(sf,"Recent P2P Success Rate : %.4f%%" ZT_EOL_S,(1.0 - ((double)unsuccessfulp2p / (double)s_rendezvousTracking.size())) * 100.0);
  1226. }
  1227. s_rendezvousTracking_l.unlock();
  1228. fprintf(sf,"Input (MiB/s) : %.4f" ZT_EOL_S,s_inputRate.perSecond(now) / 1048576.0);
  1229. fprintf(sf,"Output (MiB/s) : %.4f" ZT_EOL_S,s_outputRate.perSecond(now) / 1048576.0);
  1230. fprintf(sf,"Forwarded (MiB/s) : %.4f" ZT_EOL_S,s_forwardRate.perSecond(now) / 1048576.0);
  1231. fprintf(sf,"Discarded Forward (MiB/s) : %.4f" ZT_EOL_S,s_discardedForwardRate.perSecond(now) / 1048576.0);
  1232. fclose(sf);
  1233. std::string statsFilePath2(s_statsRoot);
  1234. statsFilePath2.append("/stats");
  1235. OSUtils::rm(statsFilePath2);
  1236. OSUtils::rename(statsFilePath.c_str(),statsFilePath2.c_str());
  1237. }
  1238. }
  1239. }
  1240. // If we received a kill signal, close everything and wait
  1241. // for threads to die before exiting.
  1242. s_run = false; // sanity check
  1243. apiServ.stop();
  1244. for(auto s=sockets.begin();s!=sockets.end();++s) {
  1245. shutdown(*s,SHUT_RDWR);
  1246. close(*s);
  1247. }
  1248. for(auto t=threads.begin();t!=threads.end();++t)
  1249. t->join();
  1250. return 0;
  1251. }