root.cpp 61 KB

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