root.cpp 46 KB

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