root.cpp 62 KB

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