root.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197
  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. * "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. * 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. 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. static int64_t s_startTime; // Time service was started
  152. static std::vector<int> s_ports; // Ports to bind for UDP traffic
  153. static int s_relayMaxHops = 0; // Max relay hops
  154. static Identity s_self; // My identity (including secret)
  155. static std::atomic_bool s_run; // Remains true until shutdown is ordered
  156. static json s_config; // JSON config file contents
  157. static std::string s_statsRoot; // Root to write stats, peers, etc.
  158. static std::string s_planet; // Planet file contents to distribute with OK(HELLO) if any
  159. static Meter inputRate;
  160. static Meter outputRate;
  161. static Meter forwardRate;
  162. static Meter siblingForwardRate;
  163. static Meter discardedForwardRate;
  164. static std::vector< SharedPtr<RootPeer> > siblings;
  165. static std::unordered_map< uint64_t,std::unordered_map< MulticastGroup,std::unordered_map< Address,int64_t,AddressHasher >,MulticastGroupHasher > > multicastSubscriptions;
  166. static std::unordered_map< Identity,SharedPtr<RootPeer>,IdentityHasher > peersByIdentity;
  167. static std::unordered_map< Address,std::set< SharedPtr<RootPeer> >,AddressHasher > peersByVirtAddr;
  168. static std::unordered_map< InetAddress,std::set< SharedPtr<RootPeer> >,InetAddressHasher > peersByPhysAddr;
  169. static std::unordered_map< RendezvousKey,int64_t,RendezvousKey::Hasher > lastRendezvous;
  170. static std::mutex s_planet_l;
  171. static std::mutex siblings_l;
  172. static std::mutex multicastSubscriptions_l;
  173. static std::mutex peersByIdentity_l;
  174. static std::mutex peersByVirtAddr_l;
  175. static std::mutex peersByPhysAddr_l;
  176. static std::mutex lastRendezvous_l;
  177. //////////////////////////////////////////////////////////////////////////////
  178. //////////////////////////////////////////////////////////////////////////////
  179. static void handlePacket(const int v4s,const int v6s,const InetAddress *const ip,Packet &pkt)
  180. {
  181. char ipstr[128],ipstr2[128],astr[32],astr2[32],tmpstr[256];
  182. const bool fragment = pkt[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] == ZT_PACKET_FRAGMENT_INDICATOR;
  183. const Address source(pkt.source());
  184. const Address dest(pkt.destination());
  185. const int64_t now = OSUtils::now();
  186. inputRate.log(now,pkt.size());
  187. if ((!fragment)&&(!pkt.fragmented())&&(dest == s_self.address())) {
  188. SharedPtr<RootPeer> peer;
  189. // If this is an un-encrypted HELLO, either learn a new peer or verify
  190. // that this is a peer we already know.
  191. if ((pkt.cipher() == ZT_PROTO_CIPHER_SUITE__POLY1305_NONE)&&(pkt.verb() == Packet::VERB_HELLO)) {
  192. std::lock_guard<std::mutex> pbi_l(peersByIdentity_l);
  193. std::lock_guard<std::mutex> pbv_l(peersByVirtAddr_l);
  194. Identity id;
  195. if (id.deserialize(pkt,ZT_PROTO_VERB_HELLO_IDX_IDENTITY)) {
  196. {
  197. auto pById = peersByIdentity.find(id);
  198. if (pById != peersByIdentity.end()) {
  199. peer = pById->second;
  200. //printf("%s has %s (known (1))" ZT_EOL_S,ip->toString(ipstr),source().toString(astr));
  201. }
  202. }
  203. if (peer) {
  204. if (!pkt.dearmor(peer->key)) {
  205. printf("%s HELLO rejected: packet authentication failed" ZT_EOL_S,ip->toString(ipstr));
  206. return;
  207. }
  208. } else {
  209. peer.set(new RootPeer);
  210. if (s_self.agree(id,peer->key)) {
  211. if (pkt.dearmor(peer->key)) {
  212. if (!pkt.uncompress()) {
  213. printf("%s HELLO rejected: decompression failed" ZT_EOL_S,ip->toString(ipstr));
  214. return;
  215. }
  216. peer->id = id;
  217. peer->lastReceive = now;
  218. peersByIdentity.emplace(id,peer);
  219. peersByVirtAddr[id.address()].emplace(peer);
  220. } else {
  221. printf("%s HELLO rejected: packet authentication failed" ZT_EOL_S,ip->toString(ipstr));
  222. return;
  223. }
  224. } else {
  225. printf("%s HELLO rejected: key agreement failed" ZT_EOL_S,ip->toString(ipstr));
  226. return;
  227. }
  228. }
  229. }
  230. }
  231. // If it wasn't a HELLO, check to see if any known identities for the sender's
  232. // short ZT address successfully decrypt the packet.
  233. if (!peer) {
  234. std::lock_guard<std::mutex> pbv_l(peersByVirtAddr_l);
  235. auto peers = peersByVirtAddr.find(source);
  236. if (peers != peersByVirtAddr.end()) {
  237. for(auto p=peers->second.begin();p!=peers->second.end();++p) {
  238. if (pkt.dearmor((*p)->key)) {
  239. if (!pkt.uncompress()) {
  240. printf("%s packet rejected: decompression failed" ZT_EOL_S,ip->toString(ipstr));
  241. return;
  242. }
  243. peer = (*p);
  244. //printf("%s has %s (known (2))" ZT_EOL_S,ip->toString(ipstr),source().toString(astr));
  245. break;
  246. }
  247. }
  248. }
  249. }
  250. // If we found the peer, update IP and/or time and handle certain key packet types that the
  251. // root must concern itself with.
  252. if (peer) {
  253. std::lock_guard<std::mutex> pl(peer->lock);
  254. InetAddress *const peerIp = ip->isV4() ? &(peer->ip4) : &(peer->ip6);
  255. if (*peerIp != ip) {
  256. std::lock_guard<std::mutex> pbp_l(peersByPhysAddr_l);
  257. if (*peerIp) {
  258. auto prev = peersByPhysAddr.find(*peerIp);
  259. if (prev != peersByPhysAddr.end()) {
  260. prev->second.erase(peer);
  261. if (prev->second.empty())
  262. peersByPhysAddr.erase(prev);
  263. }
  264. }
  265. *peerIp = ip;
  266. peersByPhysAddr[ip].emplace(peer);
  267. }
  268. const int64_t now = OSUtils::now();
  269. peer->lastReceive = now;
  270. switch(pkt.verb()) {
  271. case Packet::VERB_HELLO:
  272. try {
  273. if ((now - peer->lastHello) > 1000) {
  274. peer->lastHello = now;
  275. peer->vProto = (int)pkt[ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION];
  276. peer->vMajor = (int)pkt[ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION];
  277. peer->vMinor = (int)pkt[ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION];
  278. peer->vRev = (int)pkt.template at<uint16_t>(ZT_PROTO_VERB_HELLO_IDX_REVISION);
  279. const uint64_t origId = pkt.packetId();
  280. const uint64_t ts = pkt.template at<uint64_t>(ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP);
  281. pkt.reset(source,s_self.address(),Packet::VERB_OK);
  282. pkt.append((uint8_t)Packet::VERB_HELLO);
  283. pkt.append(origId);
  284. pkt.append(ts);
  285. pkt.append((uint8_t)ZT_PROTO_VERSION);
  286. pkt.append((uint8_t)0);
  287. pkt.append((uint8_t)0);
  288. pkt.append((uint16_t)0);
  289. ip->serialize(pkt);
  290. if (peer->vProto < 11) { // send planet file for pre-2.x peers
  291. std::lock_guard<std::mutex> pl(s_planet_l);
  292. if (s_planet.length() > 0) {
  293. pkt.append((uint16_t)s_planet.size());
  294. pkt.append((const uint8_t *)s_planet.data(),s_planet.size());
  295. }
  296. }
  297. pkt.armor(peer->key,true);
  298. 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)));
  299. outputRate.log(now,pkt.size());
  300. peer->lastSend = now;
  301. }
  302. } catch ( ... ) {
  303. printf("* unexpected exception handling HELLO from %s" ZT_EOL_S,ip->toString(ipstr));
  304. }
  305. break;
  306. case Packet::VERB_ECHO:
  307. try {
  308. if ((now - peer->lastEcho) > 1000) {
  309. peer->lastEcho = now;
  310. Packet outp(source,s_self.address(),Packet::VERB_OK);
  311. outp.append((uint8_t)Packet::VERB_ECHO);
  312. outp.append(pkt.packetId());
  313. outp.append(((const uint8_t *)pkt.data()) + ZT_PACKET_IDX_PAYLOAD,pkt.size() - ZT_PACKET_IDX_PAYLOAD);
  314. outp.compress();
  315. outp.armor(peer->key,true);
  316. 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)));
  317. outputRate.log(now,outp.size());
  318. peer->lastSend = now;
  319. }
  320. } catch ( ... ) {
  321. printf("* unexpected exception handling ECHO from %s" ZT_EOL_S,ip->toString(ipstr));
  322. }
  323. case Packet::VERB_WHOIS:
  324. try {
  325. std::vector< SharedPtr<RootPeer> > results;
  326. {
  327. std::lock_guard<std::mutex> l(peersByVirtAddr_l);
  328. for(unsigned int ptr=ZT_PACKET_IDX_PAYLOAD;(ptr+ZT_ADDRESS_LENGTH)<=pkt.size();ptr+=ZT_ADDRESS_LENGTH) {
  329. auto peers = peersByVirtAddr.find(Address(pkt.field(ptr,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH));
  330. if (peers != peersByVirtAddr.end()) {
  331. for(auto p=peers->second.begin();p!=peers->second.end();++p)
  332. results.push_back(*p);
  333. }
  334. }
  335. }
  336. if (!results.empty()) {
  337. const uint64_t origId = pkt.packetId();
  338. pkt.reset(source,s_self.address(),Packet::VERB_OK);
  339. pkt.append((uint8_t)Packet::VERB_WHOIS);
  340. pkt.append(origId);
  341. for(auto p=results.begin();p!=results.end();++p)
  342. (*p)->id.serialize(pkt,false);
  343. pkt.armor(peer->key,true);
  344. 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)));
  345. outputRate.log(now,pkt.size());
  346. peer->lastSend = now;
  347. }
  348. } catch ( ... ) {
  349. printf("* unexpected exception handling ECHO from %s" ZT_EOL_S,ip->toString(ipstr));
  350. }
  351. case Packet::VERB_MULTICAST_LIKE:
  352. try {
  353. std::lock_guard<std::mutex> l(multicastSubscriptions_l);
  354. for(unsigned int ptr=ZT_PACKET_IDX_PAYLOAD;(ptr+18)<=pkt.size();ptr+=18) {
  355. const uint64_t nwid = pkt.template at<uint64_t>(ptr);
  356. const MulticastGroup mg(MAC(pkt.field(ptr + 8,6),6),pkt.template at<uint32_t>(ptr + 14));
  357. multicastSubscriptions[nwid][mg][source] = now;
  358. //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);
  359. }
  360. } catch ( ... ) {
  361. printf("* unexpected exception handling MULTICAST_LIKE from %s" ZT_EOL_S,ip->toString(ipstr));
  362. }
  363. break;
  364. case Packet::VERB_MULTICAST_GATHER:
  365. try {
  366. const uint64_t nwid = pkt.template at<uint64_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID);
  367. //const unsigned int flags = pkt[ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS];
  368. 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));
  369. unsigned int gatherLimit = pkt.template at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_GATHER_LIMIT);
  370. if (gatherLimit > 255)
  371. gatherLimit = 255;
  372. const uint64_t origId = pkt.packetId();
  373. pkt.reset(source,s_self.address(),Packet::VERB_OK);
  374. pkt.append((uint8_t)Packet::VERB_MULTICAST_GATHER);
  375. pkt.append(origId);
  376. pkt.append(nwid);
  377. mg.mac().appendTo(pkt);
  378. pkt.append((uint32_t)mg.adi());
  379. {
  380. std::lock_guard<std::mutex> l(multicastSubscriptions_l);
  381. auto forNet = multicastSubscriptions.find(nwid);
  382. if (forNet != multicastSubscriptions.end()) {
  383. auto forGroup = forNet->second.find(mg);
  384. if (forGroup != forNet->second.end()) {
  385. pkt.append((uint32_t)forGroup->second.size());
  386. const unsigned int countAt = pkt.size();
  387. pkt.addSize(2);
  388. unsigned int l = 0;
  389. for(auto g=forGroup->second.begin();((l<gatherLimit)&&(g!=forGroup->second.end()));++g) {
  390. if (g->first != source) {
  391. ++l;
  392. g->first.appendTo(pkt);
  393. }
  394. }
  395. if (l > 0) {
  396. pkt.setAt<uint16_t>(countAt,(uint16_t)l);
  397. pkt.armor(peer->key,true);
  398. 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)));
  399. outputRate.log(now,pkt.size());
  400. peer->lastSend = now;
  401. //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);
  402. }
  403. }
  404. }
  405. }
  406. } catch ( ... ) {
  407. printf("* unexpected exception handling MULTICAST_GATHER from %s" ZT_EOL_S,ip->toString(ipstr));
  408. }
  409. break;
  410. default:
  411. break;
  412. }
  413. return;
  414. }
  415. }
  416. // If we made it here, we are forwarding this packet to someone else and also possibly
  417. // sending a RENDEZVOUS message.
  418. int hops = 0;
  419. bool introduce = false;
  420. if (fragment) {
  421. if ((hops = (int)reinterpret_cast<Packet::Fragment *>(&pkt)->incrementHops()) > s_relayMaxHops) {
  422. //printf("%s refused to forward to %s: max hop count exceeded" ZT_EOL_S,ip->toString(ipstr),dest.toString(astr));
  423. discardedForwardRate.log(now,pkt.size());
  424. return;
  425. }
  426. } else {
  427. if ((hops = (int)pkt.incrementHops()) > s_relayMaxHops) {
  428. //printf("%s refused to forward to %s: max hop count exceeded" ZT_EOL_S,ip->toString(ipstr),dest.toString(astr));
  429. discardedForwardRate.log(now,pkt.size());
  430. return;
  431. }
  432. if (hops == 1) {
  433. RendezvousKey rk(source,dest);
  434. std::lock_guard<std::mutex> l(lastRendezvous_l);
  435. int64_t &lr = lastRendezvous[rk];
  436. if ((now - lr) >= 45000) {
  437. lr = now;
  438. introduce = true;
  439. }
  440. }
  441. }
  442. std::vector< std::pair< InetAddress *,SharedPtr<RootPeer> > > toAddrs;
  443. {
  444. std::lock_guard<std::mutex> pbv_l(peersByVirtAddr_l);
  445. auto peers = peersByVirtAddr.find(dest);
  446. if (peers != peersByVirtAddr.end()) {
  447. for(auto p=peers->second.begin();p!=peers->second.end();++p) {
  448. if ((*p)->ip4) {
  449. toAddrs.push_back(std::pair< InetAddress *,SharedPtr<RootPeer> >(&((*p)->ip4),*p));
  450. } else if ((*p)->ip6) {
  451. toAddrs.push_back(std::pair< InetAddress *,SharedPtr<RootPeer> >(&((*p)->ip6),*p));
  452. }
  453. }
  454. }
  455. }
  456. if (toAddrs.empty()) {
  457. std::lock_guard<std::mutex> sib_l(siblings_l);
  458. for(auto s=siblings.begin();s!=siblings.end();++s) {
  459. if (((now - (*s)->lastReceive) < (ZT_PEER_PING_PERIOD * 2))&&((*s)->sibling)) {
  460. if ((*s)->ip4) {
  461. toAddrs.push_back(std::pair< InetAddress *,SharedPtr<RootPeer> >(&((*s)->ip4),*s));
  462. } else if ((*s)->ip6) {
  463. toAddrs.push_back(std::pair< InetAddress *,SharedPtr<RootPeer> >(&((*s)->ip6),*s));
  464. }
  465. }
  466. }
  467. }
  468. if (toAddrs.empty()) {
  469. discardedForwardRate.log(now,pkt.size());
  470. return;
  471. }
  472. if (introduce) {
  473. std::lock_guard<std::mutex> l(peersByVirtAddr_l);
  474. auto sources = peersByVirtAddr.find(source);
  475. if (sources != peersByVirtAddr.end()) {
  476. for(auto a=sources->second.begin();a!=sources->second.end();++a) {
  477. for(auto b=toAddrs.begin();b!=toAddrs.end();++b) {
  478. if (((*a)->ip6)&&(b->second->ip6)) {
  479. //printf("* introducing %s(%s) to %s(%s)" ZT_EOL_S,ip->toString(ipstr),source.toString(astr),b->second->ip6.toString(ipstr2),dest.toString(astr2));
  480. // Introduce source to destination (V6)
  481. Packet outp(source,s_self.address(),Packet::VERB_RENDEZVOUS);
  482. outp.append((uint8_t)0);
  483. dest.appendTo(outp);
  484. outp.append((uint16_t)b->second->ip6.port());
  485. outp.append((uint8_t)16);
  486. outp.append((const uint8_t *)b->second->ip6.rawIpData(),16);
  487. outp.armor((*a)->key,true);
  488. sendto(v6s,outp.data(),outp.size(),SENDTO_FLAGS,(const struct sockaddr *)&((*a)->ip6),(socklen_t)sizeof(struct sockaddr_in6));
  489. outputRate.log(now,outp.size());
  490. (*a)->lastSend = now;
  491. // Introduce destination to source (V6)
  492. outp.reset(dest,s_self.address(),Packet::VERB_RENDEZVOUS);
  493. outp.append((uint8_t)0);
  494. source.appendTo(outp);
  495. outp.append((uint16_t)ip->port());
  496. outp.append((uint8_t)16);
  497. outp.append((const uint8_t *)ip->rawIpData(),16);
  498. outp.armor(b->second->key,true);
  499. sendto(v6s,outp.data(),outp.size(),SENDTO_FLAGS,(const struct sockaddr *)&(b->second->ip6),(socklen_t)sizeof(struct sockaddr_in6));
  500. outputRate.log(now,outp.size());
  501. b->second->lastSend = now;
  502. }
  503. if (((*a)->ip4)&&(b->second->ip4)) {
  504. //printf("* introducing %s(%s) to %s(%s)" ZT_EOL_S,ip->toString(ipstr),source.toString(astr),b->second->ip4.toString(ipstr2),dest.toString(astr2));
  505. // Introduce source to destination (V4)
  506. Packet outp(source,s_self.address(),Packet::VERB_RENDEZVOUS);
  507. outp.append((uint8_t)0);
  508. dest.appendTo(outp);
  509. outp.append((uint16_t)b->second->ip4.port());
  510. outp.append((uint8_t)4);
  511. outp.append((const uint8_t *)b->second->ip4.rawIpData(),4);
  512. outp.armor((*a)->key,true);
  513. sendto(v4s,outp.data(),outp.size(),SENDTO_FLAGS,(const struct sockaddr *)&((*a)->ip4),(socklen_t)sizeof(struct sockaddr_in));
  514. outputRate.log(now,outp.size());
  515. (*a)->lastSend = now;
  516. // Introduce destination to source (V4)
  517. outp.reset(dest,s_self.address(),Packet::VERB_RENDEZVOUS);
  518. outp.append((uint8_t)0);
  519. source.appendTo(outp);
  520. outp.append((uint16_t)ip->port());
  521. outp.append((uint8_t)4);
  522. outp.append((const uint8_t *)ip->rawIpData(),4);
  523. outp.armor(b->second->key,true);
  524. sendto(v4s,outp.data(),outp.size(),SENDTO_FLAGS,(const struct sockaddr *)&(b->second->ip4),(socklen_t)sizeof(struct sockaddr_in));
  525. outputRate.log(now,outp.size());
  526. b->second->lastSend = now;
  527. }
  528. }
  529. }
  530. }
  531. }
  532. for(auto i=toAddrs.begin();i!=toAddrs.end();++i) {
  533. //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());
  534. 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) {
  535. outputRate.log(now,pkt.size());
  536. forwardRate.log(now,pkt.size());
  537. if (i->second->sibling)
  538. siblingForwardRate.log(now,pkt.size());
  539. i->second->lastSend = now;
  540. }
  541. }
  542. }
  543. //////////////////////////////////////////////////////////////////////////////
  544. //////////////////////////////////////////////////////////////////////////////
  545. static int bindSocket(struct sockaddr *const bindAddr)
  546. {
  547. const int s = socket(bindAddr->sa_family,SOCK_DGRAM,0);
  548. if (s < 0) {
  549. close(s);
  550. return -1;
  551. }
  552. int f = 1048576;
  553. while (f > 16384) {
  554. if (setsockopt(s,SOL_SOCKET,SO_RCVBUF,(const char *)&f,sizeof(f)) == 0)
  555. break;
  556. f -= 16384;
  557. }
  558. f = 1048576;
  559. while (f > 16384) {
  560. if (setsockopt(s,SOL_SOCKET,SO_SNDBUF,(const char *)&f,sizeof(f)) == 0)
  561. break;
  562. f -= 16384;
  563. }
  564. if (bindAddr->sa_family == AF_INET6) {
  565. f = 1; setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f));
  566. #ifdef IPV6_MTU_DISCOVER
  567. f = 0; setsockopt(s,IPPROTO_IPV6,IPV6_MTU_DISCOVER,&f,sizeof(f));
  568. #endif
  569. #ifdef IPV6_DONTFRAG
  570. f = 0; setsockopt(s,IPPROTO_IPV6,IPV6_DONTFRAG,&f,sizeof(f));
  571. #endif
  572. }
  573. #ifdef IP_DONTFRAG
  574. f = 0; setsockopt(s,IPPROTO_IP,IP_DONTFRAG,&f,sizeof(f));
  575. #endif
  576. #ifdef IP_MTU_DISCOVER
  577. f = IP_PMTUDISC_DONT; setsockopt(s,IPPROTO_IP,IP_MTU_DISCOVER,&f,sizeof(f));
  578. #endif
  579. #ifdef SO_NO_CHECK
  580. if (bindAddr->sa_family == AF_INET) {
  581. f = 1; setsockopt(s,SOL_SOCKET,SO_NO_CHECK,(void *)&f,sizeof(f));
  582. }
  583. #endif
  584. #if defined(SO_REUSEPORT)
  585. f = 1; setsockopt(s,SOL_SOCKET,SO_REUSEPORT,(void *)&f,sizeof(f));
  586. #endif
  587. #ifndef __LINUX__ // linux wants just SO_REUSEPORT
  588. f = 1; setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  589. #endif
  590. if (bind(s,bindAddr,(bindAddr->sa_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6))) {
  591. close(s);
  592. //printf("%s\n",strerror(errno));
  593. return -1;
  594. }
  595. return s;
  596. }
  597. static void shutdownSigHandler(int sig) { s_run = false; }
  598. int main(int argc,char **argv)
  599. {
  600. signal(SIGTERM,shutdownSigHandler);
  601. signal(SIGINT,shutdownSigHandler);
  602. signal(SIGQUIT,shutdownSigHandler);
  603. signal(SIGPIPE,SIG_IGN);
  604. signal(SIGUSR1,SIG_IGN);
  605. signal(SIGUSR2,SIG_IGN);
  606. signal(SIGCHLD,SIG_IGN);
  607. s_startTime = OSUtils::now();
  608. if (argc < 3) {
  609. printf("Usage: zerotier-root <identity.secret> <config path>" ZT_EOL_S);
  610. return 1;
  611. }
  612. {
  613. std::string myIdStr;
  614. if (!OSUtils::readFile(argv[1],myIdStr)) {
  615. printf("FATAL: cannot read identity.secret at %s" ZT_EOL_S,argv[1]);
  616. return 1;
  617. }
  618. if (!s_self.fromString(myIdStr.c_str())) {
  619. printf("FATAL: cannot read identity.secret at %s (invalid identity)" ZT_EOL_S,argv[1]);
  620. return 1;
  621. }
  622. if (!s_self.hasPrivate()) {
  623. printf("FATAL: cannot read identity.secret at %s (missing secret key)" ZT_EOL_S,argv[1]);
  624. return 1;
  625. }
  626. }
  627. {
  628. std::string configStr;
  629. if (!OSUtils::readFile(argv[2],configStr)) {
  630. printf("FATAL: cannot read config file at %s" ZT_EOL_S,argv[2]);
  631. return 1;
  632. }
  633. try {
  634. s_config = json::parse(configStr);
  635. } catch (std::exception &exc) {
  636. printf("FATAL: config file at %s invalid: %s" ZT_EOL_S,argv[2],exc.what());
  637. return 1;
  638. } catch ( ... ) {
  639. printf("FATAL: config file at %s invalid: unknown exception" ZT_EOL_S,argv[2]);
  640. return 1;
  641. }
  642. if (!s_config.is_object()) {
  643. printf("FATAL: config file at %s invalid: does not contain a JSON object" ZT_EOL_S,argv[2]);
  644. return 1;
  645. }
  646. }
  647. try {
  648. auto jport = s_config["port"];
  649. if (jport.is_array()) {
  650. for(long i=0;i<(long)jport.size();++i) {
  651. int port = jport[i];
  652. if ((port <= 0)||(port > 65535)) {
  653. printf("FATAL: invalid port in config file %d" ZT_EOL_S,port);
  654. return 1;
  655. }
  656. s_ports.push_back(port);
  657. }
  658. } else {
  659. int port = jport;
  660. if ((port <= 0)||(port > 65535)) {
  661. printf("FATAL: invalid port in config file %d" ZT_EOL_S,port);
  662. return 1;
  663. }
  664. s_ports.push_back(port);
  665. }
  666. } catch ( ... ) {}
  667. if (s_ports.empty())
  668. s_ports.push_back(ZT_DEFAULT_PORT);
  669. std::sort(s_ports.begin(),s_ports.end());
  670. int httpPort = ZT_DEFAULT_PORT;
  671. try {
  672. httpPort = s_config["httpPort"];
  673. if ((httpPort <= 0)||(httpPort > 65535)) {
  674. printf("FATAL: invalid HTTP port in config file %d" ZT_EOL_S,httpPort);
  675. return 1;
  676. }
  677. } catch ( ... ) {
  678. httpPort = ZT_DEFAULT_PORT;
  679. }
  680. std::string planetFilePath;
  681. try {
  682. planetFilePath = s_config["planetFile"];
  683. } catch ( ... ) {
  684. planetFilePath = "";
  685. }
  686. try {
  687. s_statsRoot = s_config["statsRoot"];
  688. while ((s_statsRoot.length() > 0)&&(s_statsRoot[s_statsRoot.length()-1] == ZT_PATH_SEPARATOR))
  689. s_statsRoot = s_statsRoot.substr(0,s_statsRoot.length()-1);
  690. if (s_statsRoot.length() > 0)
  691. OSUtils::mkdir(s_statsRoot);
  692. } catch ( ... ) {
  693. s_statsRoot = "";
  694. }
  695. s_relayMaxHops = ZT_RELAY_MAX_HOPS;
  696. try {
  697. s_relayMaxHops = s_config["s_relayMaxHops"];
  698. if (s_relayMaxHops > ZT_PROTO_MAX_HOPS)
  699. s_relayMaxHops = ZT_PROTO_MAX_HOPS;
  700. else if (s_relayMaxHops < 0)
  701. s_relayMaxHops = 0;
  702. } catch ( ... ) {
  703. s_relayMaxHops = ZT_RELAY_MAX_HOPS;
  704. }
  705. try {
  706. auto sibs = s_config["siblings"];
  707. if (sibs.is_array()) {
  708. for(long i=0;i<(long)sibs.size();++i) {
  709. auto sib = sibs[i];
  710. if (sib.is_object()) {
  711. std::string idStr = sib["id"];
  712. std::string ipStr = sib["ip"];
  713. Identity id;
  714. if (!id.fromString(idStr.c_str())) {
  715. printf("FATAL: invalid JSON while parsing siblings section in config file: invalid identity in sibling entry" ZT_EOL_S);
  716. return 1;
  717. }
  718. InetAddress ip;
  719. if (!ip.fromString(ipStr.c_str())) {
  720. printf("FATAL: invalid JSON while parsing siblings section in config file: invalid IP address in sibling entry" ZT_EOL_S);
  721. return 1;
  722. }
  723. ip.setPort((unsigned int)sib["port"]);
  724. SharedPtr<RootPeer> rp(new RootPeer);
  725. rp->id = id;
  726. if (!s_self.agree(id,rp->key)) {
  727. printf("FATAL: invalid JSON while parsing siblings section in config file: invalid identity in sibling entry (unable to execute key agreement)" ZT_EOL_S);
  728. return 1;
  729. }
  730. if (ip.isV4()) {
  731. rp->ip4 = ip;
  732. } else if (ip.isV6()) {
  733. rp->ip6 = ip;
  734. } else {
  735. printf("FATAL: invalid JSON while parsing siblings section in config file: invalid IP address in sibling entry" ZT_EOL_S);
  736. return 1;
  737. }
  738. rp->sibling = true;
  739. siblings.push_back(rp);
  740. peersByIdentity[id] = rp;
  741. peersByVirtAddr[id.address()].insert(rp);
  742. peersByPhysAddr[ip].insert(rp);
  743. } else {
  744. printf("FATAL: invalid JSON while parsing siblings section in config file: sibling entry is not a JSON object" ZT_EOL_S);
  745. return 1;
  746. }
  747. }
  748. } else {
  749. printf("FATAL: invalid JSON while parsing siblings section in config file: siblings is not a JSON array" ZT_EOL_S);
  750. return 1;
  751. }
  752. } catch ( ... ) {
  753. printf("FATAL: invalid JSON while parsing siblings section in config file: parse error" ZT_EOL_S);
  754. return 1;
  755. }
  756. unsigned int ncores = std::thread::hardware_concurrency();
  757. if (ncores == 0) ncores = 1;
  758. s_run = true;
  759. std::vector<std::thread> threads;
  760. std::vector<int> sockets;
  761. int v4Sock = -1,v6Sock = -1;
  762. for(auto port=s_ports.begin();port!=s_ports.end();++port) {
  763. for(unsigned int tn=0;tn<ncores;++tn) {
  764. struct sockaddr_in6 in6;
  765. memset(&in6,0,sizeof(in6));
  766. in6.sin6_family = AF_INET6;
  767. in6.sin6_port = htons((uint16_t)*port);
  768. const int s6 = bindSocket((struct sockaddr *)&in6);
  769. if (s6 < 0) {
  770. std::cout << "ERROR: unable to bind to port " << *port << ZT_EOL_S;
  771. exit(1);
  772. }
  773. struct sockaddr_in in4;
  774. memset(&in4,0,sizeof(in4));
  775. in4.sin_family = AF_INET;
  776. in4.sin_port = htons((uint16_t)*port);
  777. const int s4 = bindSocket((struct sockaddr *)&in4);
  778. if (s4 < 0) {
  779. std::cout << "ERROR: unable to bind to port " << *port << ZT_EOL_S;
  780. exit(1);
  781. }
  782. sockets.push_back(s6);
  783. sockets.push_back(s4);
  784. if (v4Sock < 0) v4Sock = s4;
  785. if (v6Sock < 0) v6Sock = s6;
  786. threads.push_back(std::thread([s6,s4]() {
  787. struct sockaddr_in6 in6;
  788. Packet pkt;
  789. memset(&in6,0,sizeof(in6));
  790. for(;;) {
  791. socklen_t sl = sizeof(in6);
  792. const int pl = (int)recvfrom(s6,pkt.unsafeData(),pkt.capacity(),0,(struct sockaddr *)&in6,&sl);
  793. if (pl > 0) {
  794. if (pl >= ZT_PROTO_MIN_FRAGMENT_LENGTH) {
  795. try {
  796. pkt.setSize((unsigned int)pl);
  797. handlePacket(s4,s6,reinterpret_cast<const InetAddress *>(&in6),pkt);
  798. } catch ( ... ) {
  799. char ipstr[128];
  800. printf("* unexpected exception handling packet from %s" ZT_EOL_S,reinterpret_cast<const InetAddress *>(&in6)->toString(ipstr));
  801. }
  802. }
  803. } else {
  804. break;
  805. }
  806. }
  807. }));
  808. threads.push_back(std::thread([s6,s4]() {
  809. struct sockaddr_in in4;
  810. Packet pkt;
  811. memset(&in4,0,sizeof(in4));
  812. for(;;) {
  813. socklen_t sl = sizeof(in4);
  814. const int pl = (int)recvfrom(s4,pkt.unsafeData(),pkt.capacity(),0,(struct sockaddr *)&in4,&sl);
  815. if (pl > 0) {
  816. if (pl >= ZT_PROTO_MIN_FRAGMENT_LENGTH) {
  817. try {
  818. pkt.setSize((unsigned int)pl);
  819. handlePacket(s4,s6,reinterpret_cast<const InetAddress *>(&in4),pkt);
  820. } catch ( ... ) {
  821. char ipstr[128];
  822. printf("* unexpected exception handling packet from %s" ZT_EOL_S,reinterpret_cast<const InetAddress *>(&in4)->toString(ipstr));
  823. }
  824. }
  825. } else {
  826. break;
  827. }
  828. }
  829. }));
  830. }
  831. }
  832. // Minimal local API for use with monitoring clients, etc.
  833. httplib::Server apiServ;
  834. threads.push_back(std::thread([&apiServ,httpPort]() {
  835. apiServ.Get("/",[](const httplib::Request &req,httplib::Response &res) {
  836. std::ostringstream o;
  837. std::lock_guard<std::mutex> l0(peersByIdentity_l);
  838. std::lock_guard<std::mutex> l1(peersByPhysAddr_l);
  839. o << "ZeroTier Root Server " << ZEROTIER_ONE_VERSION_MAJOR << '.' << ZEROTIER_ONE_VERSION_MINOR << '.' << ZEROTIER_ONE_VERSION_REVISION << ZT_EOL_S;
  840. o << "(c)2019 ZeroTier, Inc." ZT_EOL_S "Licensed under the ZeroTier BSL 1.1" ZT_EOL_S ZT_EOL_S;
  841. o << "Peers Online: " << peersByIdentity.size() << ZT_EOL_S;
  842. o << "Physical Addresses: " << peersByPhysAddr.size() << ZT_EOL_S;
  843. res.set_content(o.str(),"text/plain");
  844. });
  845. apiServ.Get("/peer",[](const httplib::Request &req,httplib::Response &res) {
  846. char tmp[256];
  847. std::ostringstream o;
  848. o << '[';
  849. {
  850. bool first = true;
  851. std::lock_guard<std::mutex> l(peersByIdentity_l);
  852. for(auto p=peersByIdentity.begin();p!=peersByIdentity.end();++p) {
  853. if (first)
  854. first = false;
  855. else o << ',';
  856. o <<
  857. "{\"address\":\"" << p->first.address().toString(tmp) << "\""
  858. ",\"latency\":-1"
  859. ",\"paths\":[";
  860. if (p->second->ip4) {
  861. o <<
  862. "{\"active\":true"
  863. ",\"address\":\"" << p->second->ip4.toIpString(tmp) << "\\/" << p->second->ip4.port() << "\""
  864. ",\"expired\":false"
  865. ",\"lastReceive\":" << p->second->lastReceive <<
  866. ",\"lastSend\":" << p->second->lastSend <<
  867. ",\"preferred\":true"
  868. ",\"trustedPathId\":0}";
  869. }
  870. if (p->second->ip6) {
  871. if (p->second->ip4)
  872. o << ',';
  873. o <<
  874. "{\"active\":true"
  875. ",\"address\":\"" << p->second->ip6.toIpString(tmp) << "\\/" << p->second->ip6.port() << "\""
  876. ",\"expired\":false"
  877. ",\"lastReceive\":" << p->second->lastReceive <<
  878. ",\"lastSend\":" << p->second->lastSend <<
  879. ",\"preferred\":" << ((p->second->ip4) ? "false" : "true") <<
  880. ",\"trustedPathId\":0}";
  881. }
  882. o << "]"
  883. ",\"role\":\"LEAF\""
  884. ",\"version\":\"" << p->second->vMajor << '.' << p->second->vMinor << '.' << p->second->vRev << "\""
  885. ",\"versionMajor\":" << p->second->vMajor <<
  886. ",\"versionMinor\":" << p->second->vMinor <<
  887. ",\"versionRev\":" << p->second->vRev << "}";
  888. }
  889. }
  890. o << ']';
  891. res.set_content(o.str(),"application/json");
  892. });
  893. apiServ.listen("127.0.0.1",httpPort,0);
  894. }));
  895. // In the main thread periodically clean stuff up
  896. int64_t lastCleaned = 0;
  897. int64_t lastWroteStats = 0;
  898. int64_t lastPingedSiblings = 0;
  899. while (s_run) {
  900. //peersByIdentity_l.lock();
  901. //peersByPhysAddr_l.lock();
  902. //printf("*** have %lu peers at %lu physical endpoints" ZT_EOL_S,(unsigned long)peersByIdentity.size(),(unsigned long)peersByPhysAddr.size());
  903. //peersByPhysAddr_l.unlock();
  904. //peersByIdentity_l.unlock();
  905. sleep(1);
  906. const int64_t now = OSUtils::now();
  907. // Send HELLO to sibling roots
  908. if ((now - lastPingedSiblings) >= ZT_PEER_PING_PERIOD) {
  909. lastPingedSiblings = now;
  910. std::lock_guard<std::mutex> l(siblings_l);
  911. for(auto s=siblings.begin();s!=siblings.end();++s) {
  912. const InetAddress *ip = nullptr;
  913. socklen_t sl = 0;
  914. Packet outp((*s)->id.address(),s_self.address(),Packet::VERB_HELLO);
  915. outp.append((uint8_t)ZT_PROTO_VERSION);
  916. outp.append((uint8_t)0);
  917. outp.append((uint8_t)0);
  918. outp.append((uint16_t)0);
  919. outp.append((uint64_t)now);
  920. s_self.serialize(outp,false);
  921. if ((*s)->ip4) {
  922. (*s)->ip4.serialize(outp);
  923. ip = &((*s)->ip4);
  924. sl = sizeof(struct sockaddr_in);
  925. } else if ((*s)->ip6) {
  926. (*s)->ip6.serialize(outp);
  927. ip = &((*s)->ip6);
  928. sl = sizeof(struct sockaddr_in6);
  929. }
  930. if (ip) {
  931. outp.armor((*s)->key,false);
  932. sendto(ip->isV4() ? v4Sock : v6Sock,outp.data(),outp.size(),SENDTO_FLAGS,(const struct sockaddr *)ip,sl);
  933. }
  934. }
  935. }
  936. if ((now - lastCleaned) > 120000) {
  937. lastCleaned = now;
  938. // Old multicast subscription cleanup
  939. {
  940. std::lock_guard<std::mutex> l(multicastSubscriptions_l);
  941. for(auto a=multicastSubscriptions.begin();a!=multicastSubscriptions.end();) {
  942. for(auto b=a->second.begin();b!=a->second.end();) {
  943. for(auto c=b->second.begin();c!=b->second.end();) {
  944. if ((now - c->second) > ZT_MULTICAST_LIKE_EXPIRE)
  945. b->second.erase(c++);
  946. else ++c;
  947. }
  948. if (b->second.empty())
  949. a->second.erase(b++);
  950. else ++b;
  951. }
  952. if (a->second.empty())
  953. multicastSubscriptions.erase(a++);
  954. else ++a;
  955. }
  956. }
  957. // Remove expired peers
  958. {
  959. std::lock_guard<std::mutex> pbi_l(peersByIdentity_l);
  960. for(auto p=peersByIdentity.begin();p!=peersByIdentity.end();) {
  961. if (((now - p->second->lastReceive) > ZT_PEER_ACTIVITY_TIMEOUT)&&(!p->second->sibling)) {
  962. std::lock_guard<std::mutex> pbv_l(peersByVirtAddr_l);
  963. std::lock_guard<std::mutex> pbp_l(peersByPhysAddr_l);
  964. auto pbv = peersByVirtAddr.find(p->second->id.address());
  965. if (pbv != peersByVirtAddr.end()) {
  966. pbv->second.erase(p->second);
  967. if (pbv->second.empty())
  968. peersByVirtAddr.erase(pbv);
  969. }
  970. if (p->second->ip4) {
  971. auto pbp = peersByPhysAddr.find(p->second->ip4);
  972. if (pbp != peersByPhysAddr.end()) {
  973. pbp->second.erase(p->second);
  974. if (pbp->second.empty())
  975. peersByPhysAddr.erase(pbp);
  976. }
  977. }
  978. if (p->second->ip6) {
  979. auto pbp = peersByPhysAddr.find(p->second->ip6);
  980. if (pbp != peersByPhysAddr.end()) {
  981. pbp->second.erase(p->second);
  982. if (pbp->second.empty())
  983. peersByPhysAddr.erase(pbp);
  984. }
  985. }
  986. peersByIdentity.erase(p++);
  987. } else ++p;
  988. }
  989. }
  990. // Remove old rendezvous tracking entries
  991. {
  992. std::lock_guard<std::mutex> l(lastRendezvous_l);
  993. for(auto lr=lastRendezvous.begin();lr!=lastRendezvous.end();) {
  994. if ((now - lr->second) > ZT_PEER_ACTIVITY_TIMEOUT)
  995. lastRendezvous.erase(lr++);
  996. else ++lr;
  997. }
  998. }
  999. }
  1000. // Write stats if configured to do so, and periodically refresh planet file (if any)
  1001. if (((now - lastWroteStats) > 15000)&&(s_statsRoot.length() > 0)) {
  1002. lastWroteStats = now;
  1003. try {
  1004. if (planetFilePath.length() > 0) {
  1005. std::string planetData;
  1006. if ((OSUtils::readFile(planetFilePath.c_str(),planetData))&&(planetData.length() > 0)) {
  1007. std::lock_guard<std::mutex> pl(s_planet_l);
  1008. s_planet = planetData;
  1009. }
  1010. }
  1011. } catch ( ... ) {
  1012. std::lock_guard<std::mutex> pl(s_planet_l);
  1013. s_planet.clear();
  1014. }
  1015. std::string peersFilePath(s_statsRoot);
  1016. peersFilePath.append("/.peers.tmp");
  1017. FILE *pf = fopen(peersFilePath.c_str(),"wb");
  1018. if (pf) {
  1019. std::vector< SharedPtr<RootPeer> > sp;
  1020. {
  1021. std::lock_guard<std::mutex> pbi_l(peersByIdentity_l);
  1022. sp.reserve(peersByIdentity.size());
  1023. for(auto p=peersByIdentity.begin();p!=peersByIdentity.end();++p) {
  1024. sp.push_back(p->second);
  1025. }
  1026. }
  1027. std::sort(sp.begin(),sp.end(),[](const SharedPtr<RootPeer> &a,const SharedPtr<RootPeer> &b) { return (a->id < b->id); });
  1028. char ip4[128],ip6[128];
  1029. for(auto p=sp.begin();p!=sp.end();++p) {
  1030. if ((*p)->ip4) {
  1031. (*p)->ip4.toString(ip4);
  1032. } else {
  1033. ip4[0] = '-';
  1034. ip4[1] = 0;
  1035. }
  1036. if ((*p)->ip6) {
  1037. (*p)->ip6.toString(ip6);
  1038. } else {
  1039. ip6[0] = '-';
  1040. ip6[1] = 0;
  1041. }
  1042. fprintf(pf,"%.10llx %21s %45s %5.4f %d.%d.%d" ZT_EOL_S,(unsigned long long)(*p)->id.address().toInt(),ip4,ip6,fabs((double)(now - (*p)->lastReceive) / 1000.0),(*p)->vMajor,(*p)->vMinor,(*p)->vRev);
  1043. }
  1044. fclose(pf);
  1045. std::string peersFilePath2(s_statsRoot);
  1046. peersFilePath2.append("/peers");
  1047. OSUtils::rm(peersFilePath2);
  1048. OSUtils::rename(peersFilePath.c_str(),peersFilePath2.c_str());
  1049. }
  1050. std::string statsFilePath(s_statsRoot);
  1051. statsFilePath.append("/.stats.tmp");
  1052. FILE *sf = fopen(statsFilePath.c_str(),"wb");
  1053. if (sf) {
  1054. fprintf(sf,"Uptime (seconds) : %ld" ZT_EOL_S,(long)((now - s_startTime) / 1000));
  1055. peersByIdentity_l.lock();
  1056. fprintf(sf,"Peers : %llu" ZT_EOL_S,(unsigned long long)peersByIdentity.size());
  1057. peersByVirtAddr_l.lock();
  1058. fprintf(sf,"Virtual Address Collisions : %llu" ZT_EOL_S,(unsigned long long)(peersByIdentity.size() - peersByVirtAddr.size()));
  1059. peersByVirtAddr_l.unlock();
  1060. peersByIdentity_l.unlock();
  1061. peersByPhysAddr_l.lock();
  1062. fprintf(sf,"Physical Endpoints : %llu" ZT_EOL_S,(unsigned long long)peersByPhysAddr.size());
  1063. peersByPhysAddr_l.unlock();
  1064. lastRendezvous_l.lock();
  1065. fprintf(sf,"Recent P2P Graph Edges : %llu" ZT_EOL_S,(unsigned long long)lastRendezvous.size());
  1066. lastRendezvous_l.unlock();
  1067. fprintf(sf,"Input BPS : %.4f" ZT_EOL_S,inputRate.perSecond(now));
  1068. fprintf(sf,"Output BPS : %.4f" ZT_EOL_S,outputRate.perSecond(now));
  1069. fprintf(sf,"Forwarded BPS : %.4f" ZT_EOL_S,forwardRate.perSecond(now));
  1070. fprintf(sf,"Sibling Forwarded BPS : %.4f" ZT_EOL_S,siblingForwardRate.perSecond(now));
  1071. fprintf(sf,"Discarded Forward BPS : %.4f" ZT_EOL_S,discardedForwardRate.perSecond(now));
  1072. fclose(sf);
  1073. std::string statsFilePath2(s_statsRoot);
  1074. statsFilePath2.append("/stats");
  1075. OSUtils::rm(statsFilePath2);
  1076. OSUtils::rename(statsFilePath.c_str(),statsFilePath2.c_str());
  1077. }
  1078. }
  1079. }
  1080. // If we received a kill signal, close everything and wait
  1081. // for threads to die before exiting.
  1082. apiServ.stop();
  1083. for(auto s=sockets.begin();s!=sockets.end();++s) {
  1084. shutdown(*s,SHUT_RDWR);
  1085. close(*s);
  1086. }
  1087. for(auto t=threads.begin();t!=threads.end();++t)
  1088. t->join();
  1089. return 0;
  1090. }