root.cpp 43 KB

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