root.cpp 49 KB

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