root.cpp 46 KB

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