root.cpp 46 KB

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